Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android checkbox listen for click before change

I have a requirement where a checkbox is displayed for a specific setting. When the user taps on the checkbox, I want to display an alert dialog. The checkbox should then only change if the user taps on the confirm button (or similar).

My point is that the OnCheckedChanged listener only fires after the checkbox has changed state, whereas I want to listen for the click before it changes state.

like image 310
Mick Byrne Avatar asked Dec 19 '22 23:12

Mick Byrne


2 Answers

you can use onTouchListener and intercept ACTION_DOWN event for showing alert. on users choice change checked state of you checkbox programatically.

example:

checkbox.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){

            //show alert
            return true; //this will prevent checkbox from changing state
        }
        return false;
    }
});

then call checkbox.setChecked(true); or checkbox.setChecked(false); as user selects yes or no.`

like image 58
Rahul Tiwari Avatar answered Feb 27 '23 05:02

Rahul Tiwari


Use this:

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked==true){
                   //Show your alert

                    }
                }else if(isChecked==false){
                    //Show your alert
                }
            }
        });
like image 38
Jas Avatar answered Feb 27 '23 05:02

Jas