您的位置:首页 > 移动开发 > Android开发

Android 下拉列表 Spinner

2012-06-05 21:50 351 查看
为了方便用户,不让用户填写这些信息,下拉列表就可以派上用场了。
在Android中开发下拉列表步骤:

1、在布局文件中定义Spinner组件

2、将可选内容通过ArrayAdapter和下拉列表框连接起来

3、获得用户选择项,设定相应的监听信息

不多说,直接上代码,如下:

public class SpinnerActivity extends Activity {
private static final String[] MCOUNTRY = {"中国","美国","日本","印度","英国"};
private TextView mTextView;
private Spinner mSpinner;
private ArrayAdapter<String> mAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTextView = (TextView)findViewById(R.id.tv);
mSpinner = (Spinner)findViewById(R.id.sp);

mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,MCOUNTRY);
mSpinner.setAdapter(mAdapter);

mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
mTextView.setText("你的国家是: " + MCOUNTRY[arg2]);
arg0.setVisibility(View.VISIBLE);

}

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

}
});
}
}


其中布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</LinearLayout>


完成后的图片如下所示:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: