Mick Byrne
Mick Byrne

Reputation: 14484

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.

Upvotes: 4

Views: 3569

Answers (5)

Rahul Tiwari
Rahul Tiwari

Reputation: 6968

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.`

Upvotes: 7

Fadils
Fadils

Reputation: 1526

You can set onClickListener and set checkbox's checked state accordingly.

    myCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // createYourDialog
            // onPositiveButtonClicked
            myCheckBox.setChecked(true);
            // onNegativeButtonClicked
            myCheckBox.setChecked(false);

            // yourDialog.show();
        }
    });

Upvotes: 1

alican akyol
alican akyol

Reputation: 288

You can try it;

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if ( isChecked )
            {
                // do anything
                // perform logic
            }

        }
    });

Upvotes: 1

Thomas R.
Thomas R.

Reputation: 8073

If would suggest to use an OnTouchListener on the checkbox. If your condition is fulfilled then you can call checkBox.performClick().

Upvotes: 1

Jas
Jas

Reputation: 3212

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
                }
            }
        });

Upvotes: 2

Related Questions