我希望能够从Spinner
中选择一个项目,并将该项目显示在ImageView
中。我试过这样做,我的示例代码如下。还有另一种方法吗?
活动类
public class Campsites extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.campsites);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Camp_Site_Facilities, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
((ImageView) findViewById(R.id.imageView1)).setImageResource(0);
((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.bergendal1);
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
布局XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/elephant" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitXY"/>
我在字符串中创建了这个
<string-array name="Camp_Site_Facilities">
<item>Berg en Dal</item>
<item>Crocodile Bridge</item>
<item>Letaba</item>
<item>Lower Sabie</item>
<item>Mopani</item>
<item>Olifants</item>
<item>Orpen</item>
<item>Pretoriuskop</item>
<item>Punda Maria</item>
<item>Satara</item>
<item>Shingwedzi</item>
<item>Skukuza</item>
</string-array>
任何帮助将不胜感激。
答案 0 :(得分:1)
检查是否有效
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code for setting the image based on the item clicked....here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});