所以我查看了微调api,但它显示我使用AdapterView处理事件,但我从未创建过自适应的。我在string.xml中创建了数组,然后使用Android进行检索:entries= @ array /arrayname
那么,如何在不创建Adapter的情况下检索用户在微调器中拾取的内容?还是我看错了?
发布于 2014-12-08 07:41:48
谷歌实现AdapterView的意思是,你必须在你的活动上实现它的OnItemSelectedListener接口,例如:
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}并且您必须将该微调器的事件侦听器设置为:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);下面是一个完整的示例:
MainActivity
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
//Spinner
private Spinner spinner;
//The array that will store the spinner items
private ArrayList<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the spinner and add its listener
spinner = (Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
//Spinner items, stored as a String array
list = new ArrayList<>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
//To populate the spinner with a list of choices, you need to specify a SpinnerAdapter in your Activity or Fragment
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
//Set the adapter to the spinner
spinner.setAdapter(adapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//To Get the selected item:
//Since the spinner items are stored inside an array
//we can get the selected item text such as item.get(position)
Toast.makeText(this, list.get(position), Toast.LENGTH_LONG).show();
}activity_main XML布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:background="#CCC"
/>
</LinearLayout>https://stackoverflow.com/questions/27349153
复制相似问题