手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

android Spinner自定义开发

时间:2024-11-13 20:48:01

1、新建一个android工程,名称SpinnerSelfShow,其他参数可以自己设置,参见下图

android Spinner自定义开发
android Spinner自定义开发

2、开始对下拉框的样式进行定义,配置布局文件item.xml,里面放入迷撞笸痉两个textview文本显示<?xml version="1.0" encod足毂忍珩ing="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <TextView android:id="@+id/one" android:layout_width="wrap_content" //适应自身宽度 android:layout_height="wrap_content" //适应自身高度 android:drawableLeft="@drawable/icon"//文本左边的图像 android:paddingRight="8dip" //距离左边的距离 android:paddingTop="8dip" //距离屏幕的距离 android:text="TextView" //显示的文本 android:textSize="25sp" /> //设置文本字体 <TextView android:id="@+id/two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="8dip" android:paddingTop="8dip" android:text="TextView" android:textSize="25sp" /></LinearLayout>

android Spinner自定义开发

3、定义实例类,Title,定义里面的属性title,info ,实现get set方法。同时在main.xml中定义Spinner控件, <Spinner android:id="@+id/spinner1" android:layout_width="fill_parent" android:layout_height="wrap_content" />

android Spinner自定义开发
android Spinner自定义开发

4、自定义适应器SelfAdapter,继承BaseAdapter,主要是实现其中的getView方法。 public View getView(int position, View view, ViewGroup arg2) { // TODO Auto-generated method//找到布局信息 LayoutInflater layout=LayoutInflater.from(mContext); view=layout.inflate(R.layout.item, null); if(view!=null) { //将文本内容填充到 item.xml中的文本显示框中 TextView one=(TextView)view.findViewById(R.id.one); TextView two=(TextView)view.findViewById(R.id.two); one.setText(list.get(position).getInfo()); two.setText(list.get(position).getTitle()); } return view; }下面是SelfAdapter的实现截图

android Spinner自定义开发
android Spinner自定义开发

5、主体函数SpinnerSelf的实现方法。 //初始化控件信息 Spinner mSpinner = (Spinner) findViewById(R.id.spinner1); textView = (TextView)findViewById(R.id.textView); // 建立数据源 List<Title> persons=new ArrayList<Title>(); persons.add(new Title("幸福", "快乐 ")); persons.add(new Title("成功", "喜悦 ")); persons.add(new Title("爱情", "美满" )); persons.add(new Title("高兴", "乐观")); // 建立Adapter绑定数据源 SelfAdapter self=new SelfAdapter(this, persons); //绑定Adapter mSpinner.setAdapter(self); //定义下拉框选中事件 mSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) { // TODO Auto-generated method stub // 获取当前选中选项对应的LinearLayout LinearLayout layout = (LinearLayout) view; // 获取其中的TextView TextView one = (TextView) layout.getChildAt(0); TextView two =(TextView)layout.getChildAt(1); textView.setText("您选中的是 "+one.getText()+":"+two.getText()); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } } );

android Spinner自定义开发
android Spinner自定义开发

6、程序编写完毕,开始运行程序,观察结果

android Spinner自定义开发
android Spinner自定义开发
android Spinner自定义开发
© 手抄报圈