在平时开发中,有时候会用到Spinner这个控件,这个东西如何用呢? 下面我举个例子做一下详细说明,希望对大家有帮助.
package com.nuaa;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerTest extends Activity implements Spinner.OnItemSelectedListener,View.OnClickListener{
private final String[] country={"china","austin","ruby","melos"};
private ArrayList<String> list=null;
Spinner spinner=null;
TextView textview=null;
ArrayAdapter<String> adapter=null;
Button btn=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = new ArrayList<String>();
for (int i = 0; i < country.length; i++)
{
list.add(country[i]);
}
spinner=(Spinner)findViewById(R.id.spinner);
textview=(TextView)findViewById(R.id.text);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spinner.setAdapter(adapter);
// adapter.setDropDownViewResource(R.layout.drop);
// spinner.setOnItemSelectedListener(this);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
public void onClick(View view){
adapter.add("qingdao");
// spinner.setAdapter(adapter);
int position=adapter.getPosition("qingdao");
spinner.setSelection(position);
}
}
我测试了,只要设置好Adapter. 就可以了,其他即使没实现setOnSelectListener 也可以正确响应选择的.无所谓.
这里需要提醒下大家. 有的时候你需要修改Adapter. 如果你的Adapter是通过对象数组构造的,那会有问题,因为系统会把你的对象数组
转换成 长度不可变 的list. 当你在Adapter 里add insert时候,这个不可变数组就会发生异常.