package cn.com.wewell.spinner;
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.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerActivity extends Activity {
private List<String> list = new ArrayList<String>();
private TextView myTextView;
private Spinner mySpinner;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项
list.add("北京");
list.add("上海");
list.add("深圳");
list.add("福州");
list.add("厦门");
myTextView = (TextView)this.findViewById(R.id.TextView_city);
mySpinner = (Spinner)this.findViewById(R.id.Spinner_city);
//第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。
adapter = new ArrayAdapter(this,R.layout.item,R.id.textViewId, list);
//第三步:为适配器设置下拉列表下拉时的菜单样式。
//adapter.setDropDownViewResource(R.layout.item); 其实也不难理解因为要指定int textViewResourceId就需要知道是在哪个layout中用int resource来表示。
//第四步:将适配器添加到下拉列表上
mySpinner.setAdapter(adapter);
//第五步:为下拉列表设置各种事件的响应
mySpinner.setOnItemSelectedListener(new SpinnerOnSelectedListener());
}
class SpinnerOnSelectedListener implements OnItemSelectedListener{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//将所选mySpinner 的值带入myTextView 中
myTextView.setText("您选择的是:"+adapter.getItem(arg2));
//将mySpinner 显示
arg0.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
myTextView.setText("NONE");
arg0.setVisibility(View.VISIBLE);
}
}
}