Android checkbox listen for click before change

若如初见. 提交于 2019-12-24 00:42:25

问题


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.


回答1:


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




回答2:


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



回答3:


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




回答4:


You can try it;

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

        }
    });



回答5:


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


来源:https://stackoverflow.com/questions/33076697/android-checkbox-listen-for-click-before-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!