jeudi 5 janvier 2017

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

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 they are checked) in the same method as the checkboxes are added, i.e. onCreate()? If this is the case, where 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();
    }

At the moment I am trying to make the buttons invisible, since I don't want to "hardcode" in the layout file that they should be invisible to start with - thought that might make it impossible to change?

And my 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);
                }
            }
        }
    }




Aucun commentaire:

Enregistrer un commentaire