How to update data in Spinner Dynamically in Andro

2019-04-14 20:35发布

问题:

This question already has an answer here:

  • How to update a spinner dynamically? 10 answers

i have added my data in array.xml file and link to

 <string-array name="state">
        <item>ANDAMAN NICOBAR ISLANDS</item>
        <item>ANDHRA PRADESH</item>
        <item>ARUNACHAL PRADESH</item>

  <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/drpstate"
        android:entries="@array/state"/>

i want to change this entries dynamically

thanks in advance ..

回答1:

Use adapter.add() to add data and then call adapter.notifyDataSetChanged() to apply changes.

    Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
    List<String> list = Arrays.asList(getResources().getStringArray(R.array.state));

    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);
    spinnerAdapter.add("DELHI");
    spinnerAdapter.notifyDataSetChanged();


回答2:

You can achieve this in Java code as follows:

  List<String> categories = new ArrayList<String>();
  categories.add("Automobile");
  categories.add("Business Services");
  categories.add("Computers");
  categories.add("Education");
  categories.add("Personal");
  categories.add("Travel");

  ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

  spinner.setAdapter(dataAdapter);

Source: http://www.tutorialspoint.com/android/android_spinner_control.htm



回答3:

You do this using a any subclass of the BaseAdapter. Assuming you want to load data from the database you use the SimpleCursorAdapter.

    String[] from = new String[]{"nameOfColumn"}; //nameOfColumn is the name of the column in cursor to display in the spinner. 
    int[] to = new int[]{android.R.id.text1};

    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter (this, android.R.layout.simple_spinner_item, null, from, to, 0);
    cursorAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
    binding.paymentChannelSpinner.setAdapter (cursorAdapter);
    binding.paymentChannelSpinner.setOnItemSelectedListener (new AdapterView.OnItemSelectedListener () {
        @Override
        public void onItemSelected (AdapterView<?> adapterView, View view, int i, long l) {
            if (i != -1) {
                Cursor c = (Cursor) adapterView.getItemAtPosition (i);

            }
        }

        @Override
        public void onNothingSelected (AdapterView<?> adapterView) {

        }
    });

after getting your data as a cursor from the database you will set the cursor to the adapter like this:

   cursorAdapter.changeCursor(cursorFromDB); 

However, if the data is in a java array you can user an Arrayadapter