我已将我的数据添加到array.xml文件中并链接到
<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"/>
我想动态更改此条目
提前感谢..
答案 0 :(得分:10)
使用adapter.add()添加数据,然后调用adapter.notifyDataSetChanged()以应用更改。
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();
答案 1 :(得分:1)
您可以在Java代码中实现此目的,如下所示:
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);
来源:http://www.tutorialspoint.com/android/android_spinner_control.htm
答案 2 :(得分:0)
您可以使用BaseAdapter的任何子类来执行此操作。假设您要从数据库加载数据,请使用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) {
}
});
将数据作为游标从数据库中获取后,您将光标设置为适配器,如下所示:
cursorAdapter.changeCursor(cursorFromDB);
但是,如果数据在java数组中,您可以使用Arrayadapter