0

单击按钮时,我需要将数据添加到 gridview 表中。我的代码:

    String[] data = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"};
    GridView gvMain;
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smena); 
          adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data);
                gvMain = (GridView) findViewById(R.id.gridView1);
                gvMain.setAdapter(adapter);
           Button but1=(Button) findViewById(R.id.button1);
            but1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                     ButtonOn (1);
                }
            });
    }

    public void ButtonOn (int Art){
        adapter.add("1");
        gvMain.setAdapter(adapter);
    }

当我单击按钮时,我的应用程序意外停止。

4

3 回答 3

1

ArrayAdapter 将数组转换为无法修改的 AbstractList(列表)。在初始化 ArrayAdapter 时使用 ArrayList 而不是使用数组。

String[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" };

    ArrayList<String> lst = new ArrayList<String>();
    GridView gvMain;

    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smena);

        lst.addAll(Arrays.asList(data));        
        adapter = new ArrayAdapter<String>(this, R.layout.title_bar, R.id.editText1,lst);

        gvMain = (GridView) findViewById(R.id.gridView1);
        gvMain.setAdapter(adapter);

        Button but1 = (Button) findViewById(R.id.button1);
        but1.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

                ButtonOn(1);
            }
        });
    }

    public void ButtonOn(int Art) {
        lst.add("1");       
        gvMain.setAdapter(adapter);
    }
于 2012-12-20T12:48:23.077 回答
0
Try This Code   

 String[] items = {"a","b","c","d","e","f"};



            Button b = (Button)findViewById(R.id.button1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    GridView gridView = (GridView)findViewById(R.id.gridView1);

                    gridView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items));

(or)

gridView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.cust,  R.id.textView1, items));

                }
            });
于 2012-12-20T12:49:59.203 回答
0

LogCat 显示什么样的错误...

如果它向您显示“空指针异常”或“无法启动活动”,那么您应该尝试在单个活动中膨胀所有项目,或者将数据正确地指向您的活动并在新活动中显示 GridView。

希望你能理解我的想法。更重要的是,不建议将活动用作活动的内容,因为它们会消耗更多的内存。我知道有很多教程都遵循相同但隐藏了缺点。

于 2012-12-20T13:15:09.397 回答