android下拉框
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/spinner"
android:layout_marginTop="20dp"
android:id="@+id/selectSpinnerValue"
android:text="获取下拉框的值"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/selectSpinnerValue"
android:layout_marginTop="20dp"
android:id="@+id/showSpinnerValue"
/>
</RelativeLayout>
Activity:
public class SpinnerActivity extends Activity implements OnClickListener{
private String[] food={"炒面","凉面","炸酱面","打卤面","手擀面"};
private TextView showSpinnerValue;
private Spinner spinner;
private String[] tel;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
spinner=(Spinner)findViewById(R.id.spinner);
showSpinnerValue=(TextView)findViewById(R.id.showSpinnerValue);
findViewById(R.id.selectSpinnerValue).setOnClickListener(this);
//从资源读取数据内容
tel=getResources().getStringArray(R.array.phonenumber);
//定义适配器
ArrayAdapter<String> adapter=new ArrayAdapter<String>(SpinnerActivity.this,
android.R.layout.simple_spinner_dropdown_item, tel);
//给控件设置适配器
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
showSpinnerValue.setText(food[arg2]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
showSpinnerValue.setText("");
}
});
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.selectSpinnerValue:
int index=spinner.getSelectedItemPosition();
Toast.makeText(this, food[index],Toast.LENGTH_LONG ).show();
break;
default:
break;
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。