Android实现下拉菜单Spinner效果
程序员文章站
2024-02-29 15:30:16
android 中下拉菜单,即如html中的
android 中下拉菜单,即如html中的<select>,关键在于调用setdropdownviewresource方法,以xml的方式定义下拉菜单要显示的模样
1.1.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <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="com.rj141.sb.kongjian.mainactivity"> <linearlayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:textsize="18dp" android:text="请选择您最喜欢的水果:" /> <spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner" /> </linearlayout> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:textsize="18dp" android:id="@+id/tv" /> </linearlayout>
spinner是下拉列表的组件
1.2.mainactivity.class
public class mainactivity extends appcompatactivity { private spinner s; string[] data=new string[]{"苹果","雪梨","西瓜","葡萄","橙子","草莓"}; private textview tv; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv= (textview) this.findviewbyid(r.id.tv); s= (spinner) this.findviewbyid(r.id.spinner); s.setadapter(new arrayadapter<string>(this,android.r.layout.simple_list_item_1,data)); s.setonitemselectedlistener(new adapterview.onitemselectedlistener() { @override public void onitemselected(adapterview<?> parent, view view, int position, long id) { string str=data[position]; tv.settext("最喜欢的水果是:"+str); } @override public void onnothingselected(adapterview<?> parent) { } }); } } s.setadapter(new arrayadapter<string>(this,android.r.layout.simple_list_item_1,data));android.r.layout.simple_list_item_1是指安卓自带的下拉列表格式,data是数据源; s.setonitemselectedlistener(new adapterview.onitemselectedlistener()){..};是下拉列表的监听
效果图:
以上就是本文的全部内容,希望对大家学习掌握android实现下拉菜单spinner组件有所帮助。