android组件之Spinner

新手上路~开通BLOG只为记录自己成长过程,写的不好勿喷~~  


一般组件都有两种方式生成,一种通过配置文件,一种通过程序动态生成,下面先贴出运行截图:


第一种方式通过配置文件生成:

main.xml中的文件配置

 <Spinner
        android:id="@+id/sp01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/city" 
        android:entries="@array/city_labels"/>  //引用配置文件中的数组资源

创建个city_data.xml文件用来保存下拉选项数组,XML文件必须在values目录下

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="city_labels">
        <item>beijing</item>
        <item>shanghai</item>
        <item>nanjing</item>
        <item>wuhan</item>
    </string-array>

</resources>
通过以上2个配置文件就能做出下拉框的效果


第二种方式通过适配器arrayadapter类功能,该类有两个主要功能:1,读取资源文件中的表列项  2,通过list集合设置选项列表

2.1通过程序获取资源文件

此时在main.xml中不在配置Spinner的其他属性

 <Spinner
        android:id="@+id/sp01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
资源文件还是通过配置文件
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="city_labels">
        <item>beijing</item>
        <item>shanghai</item>
        <item>nanjing</item>
        <item>wuhan</item>
    </string-array>

</resources>
通过程序获取选项资源
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.sp01 = (Spinner) this.findViewById(R.id.sp01);
		this.adapter = ArrayAdapter.createFromResource(this,
				R.array.city_labels,
				android.R.layout.simple_list_item_1);
		this.sp01.setPrompt("which city do you like?");//设置标题
		
		this.sp01.setAdapter(adapter);

	}


2.2 程序中动态生成选项内容,不需要任何的配置文件,全部通过程序生成
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.city_data=new ArrayList<CharSequence>();
		this.city_data.add("beijing");
		this.city_data.add("shanghai");
		this.city_data.add("nanjing");  //添加选项内容

		this.sp01 = (Spinner) this.findViewById(R.id.sp01);
		this.adapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, this.city_data);//添加适配器
		this.adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 换个风格
		this.sp01.setPrompt("which city do you like?");// 设置标题
		this.sp01.setAdapter(adapter);

	}
}



一天学一个组件~~今天任务完成睡觉











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值