安卓编程——列表选择框Spinner的使用

Spinner是一个列表选择框,该选择框不是显示下拉菜单,而是相当于弹出一个菜单供用户选择,Spinner集成了AbsSpinner,而AbsSpinner继承了AdapterView,因此他也表现出AdapterView的特征:只要为AdapterView提供Adapter则可;

Spinner的选择框信息可以由两个办法实现:第一种是提供Adapter,第二种是指定android:entries属性,该属性使用数组资源设置该列表框的列表项目。什么时候使用以上两种方法呢?

第一种:如果选择框里面的列表项目已经可以确定,则不需要使用第二种;第二种:如果需要实现运行时动态决定Spinner的列表项,则需要对进行定制,使用Adapter为Spinner提供列表项;


详细请看实例:


先使用指定android:entries的第一种方法:

layout文件比较简单:

<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"
    tools:context="com.example.testapp.MainActivity" >

    <Spinner 
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/str"
        android:prompt="@string/prompt"
        />

</LinearLayout>


该方法需要使用@array/str指定的数组资源,因此需要在res/value目录下使用xml文件来定义一份数组资源,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="str">
        <item>海贼王</item>
        <item>火影忍者</item>
        <item>死神</item>
        <item>全职猎人</item>
    </string-array>
</resources>


第一种方法比较简单不需要编写java代码。


下面是使用Adapter的第二种方法:

layout文件不需要指定android:entries属性,其他与第一种方法一样。

关于Adapter的使用,在点击打开链接这里已经使用说明过了,直接贴出代码:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {
	
	protected android.widget.Spinner spinner; 
	protected ArrayAdapter<String>adapter;
	protected String arr[]={
			"海贼王","火影忍者","死神","全职猎人"
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		spinner=(Spinner)findViewById(R.id.spinner);
		adapter=new ArrayAdapter<String>(this,R.layout.item,arr);
	    //为Spinner添加Adapter
		spinner.setAdapter(adapter); 
	}

}

而R.layout.item代码如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:textSize="18sp"
    android:padding="8dp"
    >
</TextView>
实现的效果与第一种方法一样~



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值