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

来源:互联网 发布:通达信 引用贝格数据 编辑:程序博客网 时间:2024/05/21 08:57

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[]={"海贼王","火影忍者","死神","全职猎人"};@Overrideprotected 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添加Adapterspinner.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 0
原创粉丝点击