demo06
city_data.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="city_labels"> <item>中国-北京</item> <item>中国-上海</item> <item>中国-长沙</item> </string-array> </resources> ============ string.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name" >demo06OnItemSelectedListener </string> <string name="action_settings" >Settings </string> <string name="hello_world" >Hello world! </string> <string name="city_list" >Hello world! </string> </resources> ============================ main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/info" android:text="@string/city_list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Spinner android:id="@+id/city" android:prompt="@string/city_list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:entries="@array/city_labels" /> </LinearLayout> ============================== package com.example.demo06onitemselectedlistener; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends Activity { private Spinner city= null; private TextView info = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.city=(Spinner)super.findViewById(R.id.city); this.info=(TextView)super.findViewById(R.id.info); this.city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int idx, long id) { String value = adapterView.getItemAtPosition(idx).toString(); MainActivity.this.info.setText("you best like city is:"+value); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }