I. dictionary table used to store key-value pairs
Package com. ljq. activity;
Import java. io. Serializable;
@ SuppressWarnings ("serial ")
Public class Dict implements Serializable {
Private Integer id;
Private String text;
Public Dict (){
}
Public Dict (Integer id, String text ){
Super ();
This. id = id;
This. text = text;
}
Public Integer getId (){
Return id;
}
Public void setId (Integer id ){
This. id = id;
}
Public String getText (){
Return text;
}
Public void setText (String text ){
This. text = text;
}
/**
* Why rewrite toString?
*
* When the adapter displays data, if the object passed into the adapter is not a string, the object. toString () is directly used ()
*/
@ Override
Public String toString (){
Return text;
}
}
Ii. activity Class: bind data and obtain the selected key-Value Pair
Package com. ljq. activity;
Import java. util. ArrayList;
Import java. util. List;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. View;
Import android. widget. AdapterView;
Import android. widget. ArrayAdapter;
Import android. widget. Spinner;
Import android. widget. Toast;
Import android. widget. AdapterView. OnItemSelectedListener;
Public class MainActivity extends Activity {
Private Spinner mySpinner;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MySpinner = (Spinner) findViewById (R. id. mySpinner );
List <Dict> dicts = new ArrayList <Dict> ();
Dicts. add (new Dict (1, "Test 1 "));
Dicts. add (new Dict (2, "Test 2 "));
Dicts. add (new Dict (3, "Test 3 "));
Dicts. add (new Dict (4, "Test 4 "));
ArrayAdapter <Dict> adapter = new ArrayAdapter <Dict> (this,
Android. R. layout. simple_spinner_item, dicts );
MySpinner. setAdapter (adapter );
MySpinner. setOnItemSelectedListener (new OnItemSelectedListener (){
Public void onItemSelected (AdapterView <?> Parent, View view,
Int position, long id ){
// Method for obtaining the key: mySpinner. getSelectedItem (). toString () or (Dict) mySpinner. getSelectedItem (). getId ()
// Method for obtaining the value: (Dict) mySpinner. getSelectedItem (). getText ();
Toast. makeText (MainActivity. this,
"Key:" + mySpinner. getSelectedItem (). toString () + "," + (Dict) mySpinner. getSelectedItem (). getId () +
", Value:" + (Dict) mySpinner. getSelectedItem (). getText (),
Toast. LENGTH_LONG). show ();
}
Public void onNothingSelected (AdapterView <?> Parent ){
}
});
}
}
3. Modify the main. xml layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mySpinner"/>
</LinearLayout>
4. The running result is as follows: