How to uncheck a CheckBox when marking another?

1

I wish this could not happen.

The user clicking on the other CheckBox , deactivated the one previously marked.

MainActivity.java

package genesysgeneration.umouoto;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {

    private CheckBox cb01, cb02;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cb01=(CheckBox)findViewById(R.id.cb01);
        cb02=(CheckBox)findViewById(R.id.cb02);

        addCheckBoxChecked();

    }

    public void addCheckBoxChecked(){

        cb01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(((CheckBox)v).isChecked()){



                }

            }
        });

        cb02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



            }
        });

    }

}
    
asked by anonymous 10.01.2017 / 01:27

1 answer

5

In this situation the ideal would be to use RadioButton and RadioGroup , however answering your question, using CheckBox , can be done this way:

    cb01.setChecked(true);
    cb01.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cb01.isChecked())
                cb02.setChecked(false);
            else cb02.setChecked(true);
        }
    });

    cb02.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cb02.isChecked())
                cb01.setChecked(false);
            else cb01.setChecked(true);
        }
    }); 

Remembering that it can be written in other programming logics beyond this one.

Since you did not specify the reason for being CheckBox , if it's a layout issue, you can use RadioButton and set it to CheckBox style. In this way, it would be enough to add the custom style of the button in its style.xml :

<style name="Widget.CompoundButton.CheckBox"> 
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">@android:drawable/btn_check</item>
</style>

Read more in the documentation:

10.01.2017 / 02:14