user3244162
user3244162

Reputation: 101

Android layout and checkbox

I'm working on an Android app, I have a layout that contains a CheckBox.

I wonder if I can access my CheckBox from the Java code and perform actions like checking. I have the CheckBox's resource id.

I forgot to mention that the checkbox and layout are created in java code,

I try it :

CheckBox ceb = (CheckBox)findViewById(arrListInt.get(i));
ceb.setChecked(true);

But the checkbox is not checked

Upvotes: 1

Views: 98

Answers (4)

Saif
Saif

Reputation: 7042

Actually how far i know you can access every View of our layout from the java code. And Access means full access. You can change their properties as you like. The only thing that you will need is the "id". Then just use the method

findViewById(R.id.your_id);

and then cast it to appropriate type.

Upvotes: 1

Amit Kumar Khare
Amit Kumar Khare

Reputation: 573

You should try this way:

CheckBox cb = (CheckBox) findViewById(R.id.your_cb_ID);

    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            if(buttonView.isChecked()==true){
                // Checkbox checked true
            } else {
                // Checkbox checked false
            }
        }
    });

Where : your_cb_ID is your CheckBox View ID

Upvotes: 3

Waqar Ahmed
Waqar Ahmed

Reputation: 5068

try this :

CheckBox cb = (CheckBox)findViewById(R.id.checkboxid);

if(cb.isChecked())
{
//do your work
}

Upvotes: 2

Ben Weiss
Ben Weiss

Reputation: 17922

Yes, this can be achieved. If you have a reference to your CheckBox you can call the methods of the Checkable interface: setChecked(boolean), isChecked() and toggle().

Upvotes: 1

Related Questions