Where check if CheckBox that is added dynamically is checked? (Android)

1.8k views Asked by At

I have added checkboxes dynamically in my onCreate() method. When one or more of them are checked I want two buttons to be displayed. I am new to working with Android, but from what I can tell it won't work to do this check (see if checkboxes are checked) in the same method as the checkboxes are added, i.e. onCreate(), because they can't be found, i.e. haven't been created yet? If this is the case, in what method should I do the check? I want to add the checkboxes at startup of the activity and to check if the boxes are checked all the time.

The checkboxes are added in displayEntries(db).

Here is my onCreate():

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DatabaseHandler db = new DatabaseHandler(this);
        displayEntries(db);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, AddActivity.class); //FromActivity.this
                startActivity(i);
            }
        });

        checkChecked();
    }

checkChecked():

public void checkChecked() {
        //Check whether items have been checked
        TableLayout tl = (TableLayout) findViewById(R.id.entry_table);
        for (int i = 0; i < tl.getChildCount(); i++) {
            View child = tl.getChildAt(i);
            if (child instanceof CheckBox) {
                CheckBox checkBoxChild = (CheckBox) child;
                Log.d("Checkbox", "Checkbox is found");
                if (checkBoxChild.isChecked()) {
                    Log.d("Checkbox", "working!");
                    Button button1 = (Button) findViewById(R.id.button_edit);
                    button1.setVisibility(View.INVISIBLE);
                    Button button2 = (Button) findViewById(R.id.button_delete);
                    button2.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

(At the moment I am trying to make the buttons invisible as you could see above, since I didn't want to "hardcode" in the layout file that they should be invisible to start with - thought that might make it impossible to change? But that's a later question...)

EDIT: I realised my mistake was thinking that the checkboxes where children of my TableLayout. They were in fact children of the rows in the TableLayout. Now that I managed to locate the actual checkbox, I can make the buttons disappear by setting them as invisible when creating them and visible onClick. The remaining problem is that the buttons of course stay visible even if all buttons are unchecked again. Any ideas on how to toggle the buttons on and off depending on if any of the checkboxes are checked or not?

3

There are 3 answers

4
Alex Nikiforoff On

Did not understand your question at first. Please ignore my first answer.

If you want to listen on a check box you might want to try

myCheckBox.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View view) {
        //do something
    }
});

Anything you do in onCreate() will be re-created with each activity cycle. Therefore you might want to store the state of the check box, and change that state when someone clicks on it.

EDIT after @Ingrid comment:

Looks like there are two problems that need to be solved. One is saving the state and restoring it in on activity/fragment cycle, the other is setting the buttons visible based on condition of N checkboxes.

Assuming you are working with a database object you have an option to use dynamically created check boxes to manipulate the data in your Database Object. The checkboxes represent Boolean values in your DB object or list of objects. Since the checkboxes are dynamic and represent things in your DB, it does not make much sense to store their state in two places. If you do that, things will get out of sync and you will have a nasty bug. Rather rely on the DB object instead. Thus, update your DB object when you click on a checkbox. In onResume() retrieve that DB object (from bundle or DB depending on your architecture) and set your checkboxes / button state based on the state of the DB object.

You can use onPause() to persist your db object. or persist it on click of the check box so your don't have to wary about losing the state in-between. use onResume to setup your UI component base on the current state of the db object. Last but not least, when you update your db object check if you need to show/hide the buttons. (That is if there are on fixed number of buttons but N number of check boxes.

Hope this helps.

0
Simo On
    //Use shared preference to save.
SharedPreferences preferedName=getSharedPreferences("SavedName", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferedName.edit();
                editor.putboolean("SavedName",value);
                editor.apply();
                editor.commit();
//and to retrive.
SharedPreferences preferedName=getSharedPreferences("SavedName", Activity.MODE_PRIVATE);
        boolean chkNull =preferedName.getString("SavedName",false);

and use the boolean as the value of the checkbox.

0
Omid Aminiva On

you can see check CompoundButton because CheckBox inherit from CompoundButton

https://developer.android.com/reference/android/widget/CompoundButton.html#setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener)

checkBoxChild.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });