Android Eclipse findViewByID with programmatically CheckBox

微笑、不失礼 提交于 2019-12-12 01:07:08

问题


I create a few CheckBoxes programatically like this:

    public int cb_id = 1000;

    public void create_cb()
    {

            CheckBox cb1 = new CheckBox(this);
            cb1.setText("My CheckBox");
            cb1.setId(cb_id);

            LinearLayout ll_checkbox = (LinearLayout) findViewById(R.id.ll_checkbox);

            ll_checkbox.addView(cb1);

    }

This work's fine for me, but I can't find the CheckBox with the ID...

    public void find_cb()
    {

            CheckBox cb1 = (CheckBox) findViewById(cb_id);

            String content = cb1.getText().toString();

    }

This is not working, the app is closing.


回答1:


use following code:

public void find_cb()
{
     LinearLayout ll_checkbox = (LinearLayout) findViewById(R.id.ll_checkbox);
     CheckBox cb1 = (CheckBox) ll_checkbox.findViewById(cb_id);
     String content = cb1.getText().toString();
}



回答2:


Try this..

Use

CheckBox cb1;

as Global like public int cb_id = 1000; and inside create_cb() method just use cb1 = new CheckBox(this); and find_cb() method like below

public void find_cb()
{
   String content = cb1.getText().toString();
}


来源:https://stackoverflow.com/questions/21497816/android-eclipse-findviewbyid-with-programmatically-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!