Spinner 使用

1 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:text="@string/hobby" 
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:textSize="28dip" />
    <Spinner android:id="@+id/Spinner01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

2 Activity 类 

public class SpinnerActivity extends Activity {
	
	private static final String[] m={"足球","篮球","排球","乒乓球","冰球"};  
    private TextView view ;  
    private Spinner spinner;  
    private ArrayAdapter<String> adapter;  
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spinner_test_activity);
        
        view = (TextView) findViewById(R.id.TextView01);
        spinner = (Spinner) findViewById(R.id.Spinner01);
        //将可选内容与ArrayAdapter连接起来
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);
        //设置下拉列表的风格
        adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        //设置监听器
        spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
        spinner.setPrompt("请选择人名");
        //设置默认选择项
        spinner.setVisibility(View.VISIBLE);
    }
    
    //spinner 选择监听器 
    class SpinnerSelectedListener  implements  OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int index,
				long arg3) {
			//view.setText(m[index] );
			view.setText(arg0.getItemAtPosition(index).toString() );
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
    	
    }
 
}

相关推荐