Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
选择某些内容时,Spinner 应触发“OnItemSelected”事件:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
假设这是您的带有微调器条目(即标题)和值的 xml:
<resources>
<string-array name="size_entries">
<item>Small</item>
<item>Medium</item>
<item>Large</item>
</string-array>
<string-array name="size_values">
<item>12</item>
<item>16</item>
<item>20</item>
</string-array>
</resources>
这是你的微调器:
<Spinner
android:id="@+id/size_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/size_entries" />
然后在您的代码中获取条目:
Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large
并获取值:
int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20
android:entries
让我开心。
View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();
如果您已经知道该项目是 String
,我更喜欢:
String itemText = (String) mySpinner.getSelectedItem();
在您知道是 String
的 Object
上调用 toString()
似乎比仅将 Object
转换为 String
更为迂回。
将 setOnItemSelectedListener 添加到微调器引用并获取类似的数据`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();