How to prevent a CheckBox from being checked? - android

I would like to be able to prevent a CheckBox from being selected (or to set it back to unselected), when the CheckBox is clicked
How can I achieve this?
I do not want to simply disable the checkbox. I want the user to think it is checkable, but when the user tries to check it... then I will (possibly) prevent the checkbox from being checked and display a message.

Just add the android:clickable="false" attribute in the layout xml.
So for me I have:
<CheckBox
android:id="#+id/server_is_online"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:clickable="false"
android:text="#string/server_is_online"
android:textSize="23sp" />
and it works fine.
No that's probably not how you're supposed to use a checkbox, but I am using this as a dirty hack in the prototyping stage in lieu of having a nice icon with a green tick for all good, and an evil red cross for end of the world :)

you can do something like this:
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
cb.setChecked(false);
// Code to display your message.
}
}
});

Just set it to never being clicked
cb.setClickable(false);

Try the following
CheckBox repeatChkBx =
( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
repeatChkBx.setChecked(false); // perform logic of opening message
}
}
});

this code perfect work for me
mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if ( isChecked==true )
{
buttonView.setChecked(false);
}
else
{
buttonView.setChecked(true);
}
}
}); //this code through user cant check box check/uncheck

Try this
<CheckBox
**android:background="#android:color/transparent"
**android:clickable="false"
android:id="#+id/login_access_tick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:background for removing on click ripple effect
android:clickable="false"
 for making it not clickable

In Android CompoundButton class perfomClick() toggles checked state of button.
#Override
public boolean performClick() {
toggle();
final boolean handled = super.performClick();
if (!handled) {
// View only makes a sound effect if the onClickListener was
// called, so we'll need to make one here instead.
playSoundEffect(SoundEffectConstants.CLICK);
}
return handled;
}
You can create a class which extends CheckBox and override performClick() method if you want to manually control behaviour. Because clickable=false did not work for me.

You can try View.TouchListener as a listener to the CheckBox view like so:
inner class TouchListener : View.OnTouchListener {
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (view.id) {
<Your View id> -> {
if (event.action == ACTION_DOWN) {
//do your stuff here
}
return true /*To consume click event so the checkbox doesn't get checked, you can set it checked later once you're done using setChecked(true)*/
}
}
return false
}
}
*This snippet is in Kotlin

Just include android:clickable="false" only, it will work fine.
*Note - Do not include android:focusable attribute
Check out my below working example -
<com.google.android.material.checkbox.MaterialCheckBox
android:id="#+id/chkSelected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:checked="false"
android:scaleX="1.1"
android:scaleY="1.1"
android:clickable="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>

Related

Android Studio programmatically check a Checkbox and call its OnCheckedChange

Can I programmatically check a checkbox and make it call whatever it is coded to do once checked or unchecked?
For example, if I have a checkbox like this
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
Toast.makeText(getContext(), "You checked the checkbox!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), "You unchecked the checkbox!", Toast.LENGTH_SHORT).show();
}
}
});
And then would've called
checkBox.setChecked(true);
my checkbox would appear checked but it wouldnt make the toast.
You can do any of the following
1. Create the listener object separate and call it manually when you call setChecked
2. Extract the method for implementation of onCheckedChanged and call it manually on your change.
As the name suggest setOnCheckedChangeListener, it only calls your callback if the checkbox value actually changes.
So if it's already checked (true), and then you call checkbox.setChecked(true), the value hasn't changed, so your callback won't be called.
Try to do checkbox.setChecked(false), and it should be working correctly.
That's my best guess, without seeing the rest of your code / xml.
Android widgets' click or touch events are not simulated. you can change states of of widgets like disabling ,enabling ,checked or unchecked programmatically but todo any task when state changes , you have to change their states manually by touching on that widget.
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(getContext(), "You checked the checkbox!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "You unchecked the checkbox!", Toast.LENGTH_SHORT).show();
}
}
});
Just Cheked it. it will work for me.
if you add checkboxes in LinearLayout (let's call it checkLayout) like this :
val widget = AppCompatCheckBox(checkLayout.context)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
widget.tag = "something you can specify later"
checkLayout.addView(widget)
the code for get the selected checkbox is like this:
checkLayout.children.forEach { cb ->
if(cb is AppCompatCheckBox && cb.isChecked){
// here you have your checkbox and by tag maybe you can do whatever you want
}
}
and for dynamic added RadioButton you can add them in RadioGroup (let's call it radioLayout) and get the selected like :
val rb: AppCompatRadioButton? = radioLayout.findViewById(radioLayout.checkedRadioButtonId)
if(rb.tag == "something"){
//your code here
}

CheckBox OnLongClick Behavior

I have a list of items disposed vertically. Each item has a CheckBox and a TextView.
I'm trying to achieve a LongClick behavior for the CheckBox. More precisely i want it to change it with a trash icon while is LongClicked. On release it must become again a checkBox and also maintain the Check/Uncheck behavior on simple click.
How can i achieve that? How many approaches are there?
I apriciate any king of help!
I tried to just use setBackgroud() function, but it would just draw under the existing checkbox view, with the box still remaining on the top.
cb.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Resources res = tmp_context.getResources();
Drawable drawable = res.getDrawable(R.mipmap.ic_trash);
cb.setBackground(drawable);
return false;
}
});
UPDATE
First Put your chekcbox inside a framelayout :
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/one"
android:id="#+id/fl">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Two"
android:longClickable="true"
android:id="#+id/two"/>
</FrameLayout>
you could use LongClickListener and OnTouchListener:
private View.OnLongClickListener pressHoldListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View pView) {
// Do something when your hold starts here.
isSpeakButtonLongPressed = true;
mFrameLayout.setBackgroundResource(R.drawable.trash_can);
yourCheckBox.setVisibility(VIEW.INVISIBLE);
return true;
}
};
private View.OnTouchListener pressTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View pView, MotionEvent pEvent) {
pView.onTouchEvent(pEvent);
// We're only interested in when the button is released.
if (pEvent.getAction() == MotionEvent.ACTION_UP) {
// We're only interested in anything if our speak button is currently pressed.
if (isSpeakButtonLongPressed) {
// Do something when the button is released.
yourCheckBox.setVisibility(View.VISIBLE);
mFrameLayout.setBackground(null);
isSpeakButtonLongPressed = false;
}
}
return false;
}
};
Inside you onCreate() :
yourCheckBox.setOnLongClickListener(pressHoldListener);
yourCheckBox.setOnTouchListener(pressTouchListener);
Also add
android:longClickable="true"
to your checkbox xml.

CheckBox replace setOnCheckedChangeListener with setOnLongClickListener

I have a CheckBox that I need to respond to OnLongClickListener instead of OnCheckedChangeListener. How do I do that? Right now even though I implement the OnLongClickListener, the CheckBox still toggles when a user clicks it. I want the toggle to happen on longClick only as in
checkBox.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
checkBox.setChecked(!checkBox.isChecked());
...
return true;
}
});
I would suggest two things...
Not sure if they will work. I did not tested.
Maybe you can disable the click on layout file. Enable only the long click.
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:longClickable="true"
..... />
Or, you can override onCheckedChangeListener to do not take any action.
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBox.setChecked(!isChecked);
}
});

Android SwitchCompat onCheckedChangeListener doesn't work

This is my code and it doesn't work for me.
I use code from this example.
Xml -
<android.support.v7.widget.SwitchCompat
android:id="#+id/visibility_switch"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_marginRight="#dimen/mat_card_padding"
app:showText="false" />
And code:
mVisibilitySwitchCompat = (SwitchCompat) findViewById(R.id.visibility_switch);
mVisibilitySwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// this method doesn't work!
if (isChecked) {
mVisibilityTextView.setText(getString(R.string.visibility_on));
} else {
mVisibilityTextView.setText(getString(R.string.visibility_off));
}
}
});
Instead of using a listener, try the setTextOff() and setTextOn() methods. The Switch will automatically handle setting the correct one when the checked state changes.

Android disable button when checkbox not checked

I have a multiple checkbox and a button. What should I do to disable the button if none of the checkbox is check and enable the button if it's checked?
Try with this,
Button mButton=(Button)findViewById( R.id.button01);
CheckBox mCheckBox= ( CheckBox ) findViewById( R.id.checkbox01);
mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
mButton.setEnabled(true);
}else{
mButton.setEnabled(false);
}
}
});
When you enter in that view make the button disabled (in your XML), and whenever user hit any of the check-boxes manage one global variable e.g if the global count is > 1 then make the button enable in that activity.
Manage the global variable in a way that if user is turning on the check box then increment it and if he is turning off the checkbox decrease the counter.
I hope you got the concept.
Basically it is all about managing the count how many checkboxes are turned on; if more then one is turned on make the button enabled else make it disabled.
Instead of enabling and disabling the button you can use setVisibility() method for button.
In the following manner.
Button btn =(Button)findViewById( R.id.mybutton);
CheckBox checkBox= ( CheckBox ) findViewById( R.id.checkbox01);
mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
btn.setVisibility(VISIBLE);
}
else{
btn.setVisibility(GONE);
}
}
});
By using this method you can set the visibility of your view.Your button will be visible only if checkBox is cheaked otherwise your button will not be visible.Let me know it works or not for you.
Use this:
myButton.setEnabled(false);
See this question for more details.
you can disable button by using below code.
mBtn.setEnabled(false);
and can enable it later by using below code
mBtn.setEnabled(true);
mCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mButton.setEnabled(isChecked);
}
});
as simple as that :)
try this
termsAndConditionsCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (termsAndConditionsCheckBox.isChecked() && privacyPolicyCheckBox.isChecked()){
agreebutton.setEnabled(true);
agreebutton.setTextColor(getResources().getColor(android.R.color.white));
agreebutton.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
}
else {
agreebutton.setEnabled(false);
agreebutton.setTextColor(getResources().getColor(android.R.color.white));
agreebutton.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
}
}
});
privacyPolicyCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (termsAndConditionsCheckBox.isChecked() && privacyPolicyCheckBox.isChecked()){
agreebutton.setEnabled(true);
agreebutton.setTextColor(getResources().getColor(android.R.color.white));
agreebutton.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
}
else {
agreebutton.setEnabled(false);
agreebutton.setTextColor(getResources().getColor(android.R.color.white));
agreebutton.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
}
}
});

Categories

Resources