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?