vendredi 22 janvier 2016

How to programatically check a Checkbox in Android?

i was searching on the net for this for nearly 2 hours, but couldn't find anything working for me.

simple, I have an android App, with a listview, that includes checkboxes.

Now, when I click a button, all I want is that one checkbox gets checked (and that this is visible on the screen) No matter what i tried so far, the checkbox just won't get checked.

thats my code:

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);

}

}




Aucun commentaire:

Enregistrer un commentaire