最近 才学完了Spinner 今天和大家分享下我的学习成果吧 做的一般般 很简单的
Spinner 提供一个下拉列表供用户进行选择,这样可以减少屏幕的占有空间
Spinner可以很大的提高用户的体验性
Step 1;
先建立一个Android工程
本人一般习惯先写好XML代码先
main.xml如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${packageName}.${activityClass}" >
<EditText
android;id="text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请选择颜色”/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:promt="@string/选择颜色"/>
</LunearLayout/>
好了xml布局文件写好了
接下来写到主要部分了
Java代码部分如下
public class MySpinner extends Activity implements OnItemSelectedListener{
/**
*这是一个小的Spinner程序
*
*/
//定义一个String[] 数组 构成下拉列表的内容
String [] colors = {" 红色",“黄色”,”绿色“,“白色”,“青色”};
private static Spinner Spinner ;
private static EditText text ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过Id获取组件
spinner = (Spinner)findViewById(R.id.spinner);
text = (EditText)findViewById(R.id.text);
//创建一个ArrayAdapter适配器
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,android.R.layout.simple_spinner_item,colors);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//为Spinner设置适配器
spinner.setAdapter(adapter);
//获取EditText 组件
text = (EditText)findViewById(R.id.text);
//为Spinner绑定监听器
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?>patent,View view,int position,long Id){
text.setText(color[position]);
}
});
}
}