这里提供了一个基本思路,用来解决向spinner中动态增加和删除内容的方法,重点是要传入adapter的资源是ArrayList,然后调用Adapter的add()和remove()方法。
package tjj.spinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Test_spinner3Activity extends Activity
{
//用一个字符串数组来保存一些城市
private String[] citise = { "成都", "上海", "北京", "重庆" };
private TextView tv;
private EditText et;
private Button add, delete;
private Spinner spinner;
private ArrayAdapter<String> adapter;
//真正的字符串数据将保存在这个list中
private List<String> all;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
add = (Button) findViewById(R.id.add);
delete = (Button) findViewById(R.id.delete);
//将字符数组中的对象导入到list中,才能进行动态控制
all = new ArrayList<String>();
for (int i = 0; i < citise.length; i++)
{
all.add(citise[i]);
}
//这里需要给出View界面的资源引用,经过实验 全部使用了自己定义的格式是可以的
adapter = new ArrayAdapter<String>(this, R.layout.myspinner, all);
adapter.setDropDownViewResource(R.layout.myspinner);
spinner = (Spinner) findViewById(R.id.my_spinner);
spinner.setAdapter(adapter);
add.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String newString = et.getText().toString();
//如果输入的城市已经存在,则不再输入
for (int i = 0; i < adapter.getCount(); i++)
{
if (newString.equals(adapter.getItem(i)))
return;
}
if (!newString.equals(""))
{
//将新值添加到adapter中
adapter.add(newString);
/*取得添加的值的位置*/
int position = adapter.getPosition(newString);
/*将spinner定位到添加值的位置*/
spinner.setSelection(position);
et.setText("");
}
}
});
delete.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
/*如果spinner非空*/
if (spinner.getSelectedItem() != null)
{
adapter.remove(spinner.getSelectedItem().toString());
et.setText("");
if (adapter.getCount() == 0)
{
tv.setText("");
}
}
}
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
//将textview中这信息变为选择的内容
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
tv.setText(arg0.getSelectedItem().toString());
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
}
在此提供自己写的 myspinner.xml中的内容
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:singleLine="true"
style="?android:attr/spinnerDropDownItemStyle" />