我在网上搜索了近2个小时,但找不到任何对我有用的东西。如何以编程方式检查Android中的复选框?
简单,我有一个android应用程序,与listview,其中包括复选框。
现在,当我点击一个按钮,我只想要一个复选框被检查(并且这在屏幕上是可见的) 无论我迄今为止尝试了什么,复选框都不会被检查。
这就是我的代码:
public class MainActivity extends Activity {
SparseArray<Group> groups = new SparseArray<Group>();
List<String> checkedMedia = new ArrayList<String>();
ExpandableListView listView;
MyExpandableListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createData();
listView = (ExpandableListView) findViewById(R.id.listView);
adapter = new MyExpandableListAdapter(this,
groups);
listView.setAdapter(adapter);
listView.expandGroup(0);
}
public void onCheckboxClicked(View view) {
CheckBox checkBox = (CheckBox) view;
boolean checked = checkBox.isChecked();
View chBoxParent = (View) checkBox.getParent();
TextView textView = (TextView) chBoxParent.findViewById(R.id.textView1);
String medium = textView.getText().toString();
if (checked) {
Toast.makeText(this, "checked: " + medium, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "unchecked: " + medium, Toast.LENGTH_SHORT).show();
}
}
public void onButtonClicked(View view) {
View view0 = adapter.getChildView(0, 0, false, null, null);
CheckBox cb0 = (CheckBox) view0.findViewById(R.id.checkBox);
cb0.setChecked(true);
cb0.setWillNotDraw(false);
cb0.invalidate();
Toast.makeText(this, "button clicked", Toast.LENGTH_SHORT).show();
}
public void createData() {
Group group = new Group("Test ");
for (int i = 0; i < 5; i++) {
group.children.add("Sub Item" + i);
}
groups.append(0, group);
}
}
你需要设置CompoundButton.OnCheckedChangeListener的复选框,并没有onClickListener –
是否要将复选框设置为选中状态当您点击按钮时,什么是所有项目在列表视图中都可见? – Vishwa