如何添加项目到微调的ArrayAdapter? [英] how to add item to Spinner's ArrayAdapter?

查看:147
本文介绍了如何添加项目到微调的ArrayAdapter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个EditText上,一个按钮和一个微调。当单击该按钮,微调将添加名为您在EditText上进入了一个新的项目。但这里是一个问题,我adapter.add()方法似乎不起作用......这是我的code:

i had a EditText , a button and a spinner . When click the button , the spinner will add a new item with name you entered in the EditText. But here is the question, my adapter.add() method seems doesn't work...here is my code:

public class Spr extends Activity {
Button bt1;
EditText et;
ArrayAdapter<CharSequence> adapter;
Spinner spinner;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    bt1 = (Button)this.findViewById(R.id.bt1);
    et = (EditText)this.findViewById(R.id.et);  
    spinner = (Spinner)this.findViewById(R.id.spr);

    adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);

    bt1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String temp = et.getText().toString();

            adapter.add(temp);
            adapter.notifyDataSetChanged();
            spinner.setAdapter(adapter);

        }
    });


    spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {

            Toast.makeText(parent.getContext(), "The planet is " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }});
}

}

感谢! ...还是waitting

thanks! ...still waitting

推荐答案

当您创建了ArrayAdapter您还没有指定一个可调整大小的列表来,所以当你添加(),它可以不增加它的大小和投一个UnsupportedOperationException异常。

When you have created your ArrayAdapter you haven't assigned a resizeable List to it, so when you do add() it cannot increment the size of it and throws a UnsupportedOperationException.

尝试是这样的:

List<CharSequence> planets = new ArrayList<CharSequence>();
adapter = new ArrayAdapter<CharSequence>(context,
                       R.array.planets_array, planets);
//now you can call adapter.add()

您应该使用一个列表。对于数组等的CharSequence [],你会得到相同的UnsupportedOperationException异常的异常。

You should use a List. With an Array such as CharSequence[] you would get the same UnsupportedOperationException exception.

这篇关于如何添加项目到微调的ArrayAdapter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆