Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

android - How to do something when a checkbox change state?

This is my code:

    <CheckBox
        android:id="@+id/sprint_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sprint_game" />

    <CheckBox
        android:id="@+id/marathon_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/marathon" />

    <CheckBox
        android:id="@+id/never_ending_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/never_ending" />

What i want to do is "detect" when one of these is checked and then set the other two to "disable", so the user can select only one at time. I tried to use the ".setOnCheckedChangeListener", but i can't do that, can someone help me with some code? Thanks a lot guys!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the way you are notified about checked changes:

CheckBox check = findViewById(R.id.sprint_checkbox);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //do stuff

        }
    });

You can also let your activity implements the OnCheckedChangeListener interface and then:

CheckBox check1 = findViewById(R.id.sprint_checkbox);
CheckBox check2 = findViewById(R.id.marathon_checkbox); 
CheckBox check3 = findViewById(R.id.never_ending_checkbox);

check1.setOnCheckedChangeListener(this);
check2.setOnCheckedChangeListener(this);
check3.setOnCheckedChangeListener(this);

Overriding the interface method:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    switch(buttonView.getId()){
               case R.id.sprint_checkbox:
                 //do stuff
               break;
               case R.id.marathon_checkbox:
                 //do stuff
               break;
               case R.id.never_ending_checkbox:
                //do stuff
               break;

            }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...