问题
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