Dev_Cob
Dev_Cob

Reputation: 111

How to stop disabling a toggle button if it is clicked in checked state?

In my current design, I have used 2 toggle buttons to switch between 2 fragments. The expectation is- if 1st button is checked, only user can select the 2nd button. If user again clicks the 1st button, no action should be taken. The 1st button should not be disabled.

In my current design, if I click on the 1st button when it is already checked, the button is unchecked.

enter image description here

Activity.java

        appsToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            if(checked) {
                favToggleButton.setChecked(false);
                loadFrag(new AppDrawerGridFragment(), 1);
            }
        }
    });


   favToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
           if(checked)
           {
               appsToggleButton.setChecked(false);
               loadFrag(new FavouriteAppsFragment(), 1);
           }
       }
   });

Upvotes: 0

Views: 115

Answers (1)

Nguyễn Quang Thọ
Nguyễn Quang Thọ

Reputation: 201

you can use setCLickable function to disable click on a button when it already checked Here is my code in kotlin

        binding.btn1.isClickable = binding.btn1.isChecked.not()
        binding.btn2.isClickable = binding.btn2.isChecked.not()

        binding.btn1.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                binding.btn1.isChecked = true
                binding.btn2.isChecked = false
                binding.btn1.isClickable = false
                binding.btn2.isClickable = true
            }
        }
        binding.btn2.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                binding.btn1.isChecked = false
                binding.btn2.isChecked = true
                binding.btn1.isClickable = true
                binding.btn2.isClickable = false
            }
        }

in this code, i setClickable for btn1, btn2 everytime it change the check state -> if btn1 is checked so btn1 isClickable = false

Upvotes: 0

Related Questions