android 数组使用,android-配置spinner以使用数组

与其使用双数组方法,不如用已知类型的对象以编程方式填充ArrayAdapter并使用它。我写了一个类似性质的教程(底部的链接)来完成这项工作。最基本的前提是创建一个Java对象数组,告诉SPONEN,然后直接从SPEnter类使用这些对象。在我的示例中,我有一个表示“状态”的对象,其定义如下:

package com.katr.spinnerdemo;

public class State {

// Okay, full acknowledgment that public members are not a good idea, however

// this is a Spinner demo not an exercise in java best practices.

public int id = 0;

public String name = "";

public String abbrev = "";

// A simple constructor for populating our member variables for this tutorial.

public State( int _id, String _name, String _abbrev )

{

id = _id;

name = _name;

abbrev = _abbrev;

}

// The toString method is extremely important to making this class work with a Spinner

// (or ListView) object because this is the method called when it is trying to represent

// this object within the control. If you do not have a toString() method, you WILL

// get an exception.

public String toString()

{

return( name + " (" + abbrev + ")" );

}

}

然后,可以用这些类的数组填充微调器,如下所示:

// Step 1: Locate our spinner control and save it to the class for convenience

// You could get it every time, I'm just being lazy... :-)

spinner = (Spinner)this.findViewById(R.id.Spinner01);

// Step 2: Create and fill an ArrayAdapter with a bunch of "State" objects

ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,

android.R.layout.simple_spinner_item, new State[] {

new State( 1, "Minnesota", "MN" ),

new State( 99, "Wisconsin", "WI" ),

new State( 53, "Utah", "UT" ),

new State( 153, "Texas", "TX" )

});

// Step 3: Tell the spinner about our adapter

spinner.setAdapter(spinnerArrayAdapter);

您可以按如下方式检索所选项目:

State st = (State)spinner.getSelectedItem();

现在你有了一个真正的Java类来处理。如果要在微调器值更改时截取,只需实现OnItemSelectedListener并添加适当的方法来处理事件。

public void onItemSelected(AdapterView> parent, View view, int position, long id)

{

// Get the currently selected State object from the spinner

State st = (State)spinner.getSelectedItem();

// Now do something with it.

}

public void onNothingSelected(AdapterView> parent )

{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值