Spinner簡單實例
參考文章在此
見下圖
一個TextView與一個Spinner,spinner內容包含三個選項,而TextView將所選到的項目名稱顯示出來。
程式碼:
參考文章在此
見下圖
一個TextView與一個Spinner,spinner內容包含三個選項,而TextView將所選到的項目名稱顯示出來。
程式碼:
public class SpinnerEx extends Activity {
private Spinner spinner;
private TextView textView;
private ArrayAdapter<String> adapter;
private List< String> list=new ArrayList< String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex);
textView=(TextView) findViewById(R.id.textView);
spinner=(Spinner)findViewById(R.id.spinner);
//添加列表內容
list.add("option1");
list.add("option2");
list.add("option3");
//為spinner建立adapter
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
list);
//設定下拉選單樣式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//設定adapter
spinner.setAdapter(adapter);
//spinner事件處理
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* 将所选mySpinner 的值带入myTextView 中*/
textView.setText("您选择的是:"+ adapter.getItem(position));
/* 将mySpinner 显示*/
parent.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
textView.setText("NONE");
parent.setVisibility(View.VISIBLE);
}
});
spinner.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
/* 将mySpinner 隐藏,不隐藏也可以,看自己爱好*/
v.setVisibility(View.INVISIBLE);
return false;
}
});
spinner.setOnFocusChangeListener(new OnFocusChangeListener(){
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
v.setVisibility(View.VISIBLE);
}
});
}
}
留言
張貼留言