Activity:
1 <LinearLayout 2 xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.top4_4.MainActivity" > 8 <TextView 9 android:layout_width="fill_parent" 10 android:gravity="center_vertical" 11 android:layout_height="30dp" 12 android:paddingLeft="5dp" 13 android:background="#FFA500" 14 android:text="Spinner" /> 15 <Spinner 16 android:id="@+id/sp" 17 android:layout_width="fill_parent" 18 android:layout_height="50dp" 19 android:layout_marginTop="20dp"/> 20 <TextView 21 android:id="@+id/tv" 22 android:layout_width="fill_parent" 23 android:gravity="center_vertical" 24 android:layout_height="30dp" 25 android:paddingLeft="5dp" 26 android:text="" 27 /> 28 </LinearLayout>
JAVApublic class MainActivity extends Activity private Spinner sp;
private TextView tv; private ArrayAdapter aa; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //定义数据源 String []balls=new String[]{"","足球","篮球","棒球"}; sp=(Spinner) findViewById(R.id.sp); tv=(TextView) findViewById(R.id.tv); //找到数据源 aa=new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item,balls); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //给Spinner赋值数据 sp.setAdapter(aa); //当点击时弹出选择列表 sp.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub
//给TextView选中的数据 tv.setText(aa.getItem(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub tv.setText("没有选中任何数据!"); } });