setOnItemSelecctedListener不适用于微调器。以下是mainactivity.java中的代码。我使用entries选项在xml文件中填充了微调器。选择项目时,不会显示显示所选项目的Toast消息。
public class MainActivity extends ActionBarActivity{
String[] presidents;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
if(s1 != null){
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
}
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Spinner Element -->
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/presidents"
android:drawSelectorOnTop="true"
/>
</LinearLayout>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string-array name = "presidents">
<item>eisenhower</item>
<item>kennedy</item>
</string-array>
</resources>
答案 0 :(得分:0)
那是因为您的Spinner s1
为空。
您的xml代码:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
/>
在“活动”中,您使用ID spinner1
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
所以这里s1将为null。
你检查一下:
if(s1 != null){
s1.setAdapter(adapter);
...
}
只需将您的ID更改为spinner
:
Spinner s1 = (Spinner) findViewById(R.id.spinner);
因此s1
不会是null
,并且会使用适配器填充数据。
希望它有所帮助。
注:
如果片段中有spinner1,则需要执行以下操作:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_main, container, false);
Spinner s1 = (Spinner) v.findViewById(R.id.spinner1);
return container;
}