|
当在某个网站注册账号的时候,网站会让我们提供性别,生日,城市等信息,为了方便,就提供了一个下拉列表供我们选择,在Android也同样有这样的功能,这就是Spinner下拉列表
在编码的同时,首先需要在布局中定时Spinner组件,然后将可选内容通过ArrayAdapter和下拉列表连接起来,最后要获得用户选择的选项,我们需要设计事件监听器setOnItemSelectedListener并实现onItemSelected,从而获得用户所选择的内容,最后通过setVisibility方法设置当前的显示项
SpinnerTest.java
Java代码
package org.hualang.Spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerTest extends Activity {
/** Called when the activity is first created. */
private static final String[] citys={"杭州","北京","成都","大连","深圳","南京"};
private TextView text;
private Spinner spinner;
private ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.text);
spinner=(Spinner)findViewById(R.id.spinner);
//将可选内容与ArrayAdapter连接
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,citys);
//设置下拉列表风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将adapter添加到spinner中
spinner.setAdapter(adapter);
//添加Spinner事件监听
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
text.setText("你所在的城市是:"+citys[arg2]);
//设置显示当前选择的项
arg0.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
复制代码
main.xml
Java代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
androidrientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您所在的城市"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
</LinearLayout>
复制代码
运行结果:
|
|