android示例之Spinner

来源:互联网 发布:淳中科技矩阵 编辑:程序博客网 时间:2024/04/28 04:00

Spinner就是相当于Java中的CheckBox,可以作为显示下拉选出现。

本次的效果图是:


代码里面都有详细注解:

public class SimpleSpinner extends Activity implements OnClickListener{private String[] quenInfo={"李永川","周万里","杨万里","关天宇"};private TextView textView;private Spinner spinner;private ArrayAdapter<String> adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.simple);//得到显示的文本对象textView=(TextView)findViewById(R.id.targetNumber);//得到要点击的spinner对象spinner=(Spinner)findViewById(R.id.targetSpinner);//将要显示的选项内容和ArrayAdapter关联起来(当前Context,显示风格,显示选项)adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,quenInfo);//设置点击后的下拉列表的风格样式adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);//设置Spinner的ArrayAdapterspinner.setAdapter(adapter);//添加Spinner选项点击的监听事件spinner.setOnItemSelectedListener(new ClickListener());//设置Spinner显示(默认显示)spinner.setVisibility(View.VISIBLE);}//监听点击Spinner选项的类class ClickListener implements OnItemSelectedListener{/** * 监听改变Spinner选项的方法 * arg0 : The AdapterView that the selection happened,这里我们可以看做是下拉框 * arg1:The View within the AdapterView that was clicked,对应就是ArrayAdapter构造函数中的第二个参数android.R.layout.simple_spinner_item * arg2:The position of the view in the adapter,选择的选项的序号 * arg3:The row id of the item that is selected,被选条目的行号 */public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {textView.setText("中国最好舍友是:"+quenInfo[arg2]);System.out.println("AdapterView.arg0="+arg0);System.out.println("View.arg1="+arg1);System.out.println("arg2="+arg2);System.out.println("arg3="+arg3);System.out.println("****************************");}public void onNothingSelected(AdapterView<?> arg0) {}}public void onClick(View v) {}}

布局文件为:

<?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/targetNumber"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="60sp"        android:layout_marginRight="20sp"/><Spinner     android:id="@+id/targetSpinner"    android:layout_width="200sp"    android:layout_height="wrap_content"    android:layout_marginLeft="60sp"    android:layout_marginRight="20sp"/></LinearLayout>


0 0
原创粉丝点击