Im new to android and I don't get the code on the developers website about this really, I just want to check if the state of the toggle button is on or off. I have the following scenario
if (isCheckedToggleButton?)
{
// do something
}
else
{
// do something else
}
And a method as the guide suggests
public void onToggleClicked(View view)
{
boolean on = ((ToggleButton)view).isChecked();
if(on) {
return;
} else {
}
}
So I just want to see if the toggle button is on or off so I can decide whether to execute the code inside the if or the else. Unfortunately the method provided by the android guide is a void so it doesn't return a boolean. How can I still check the state?
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lift"
android:textOff="Uit"
android:textOn="Aan"
android:id="#+id/switchLift" android:layout_below="#id/btnEindpunt"
android:layout_alignLeft="#+id/btnEindpunt"/>
Use it like this
myToggleButton.setOnCheckedChangeListener( new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
{
if(isChecked)
// Do something
else
// Do the other thing
}
});
Change
ToggleButton myToggleButton = ((ToggleButton) findViewById(R.id.switchLift));
to
Switch myToggleButton = ((Switch) findViewById(R.id.switchLift));
Also change isChecked to something else like mIsChecked or inside the listener use YourClassName.this.isChecked for changing its value. There is already a local variable with same name.
Related
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
}
I have 1 activity and 3 fragments in this activity.
In 3 fragments I have booleans returning true when checkbox is checked or edittext is not empty..
I want to unable button when editTexts are not empty and my checkbox is checked..
When I added something like sexMan.isChecked() to method EditTextCompleted()
my app crushing....
So how can I connects this conditions in one place?
Checkbox Listener
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
mSendInfoFromBmrFragment.sexChecked(true);
switch (buttonView.getId()){
case R.id.sexMan:
mSendInfoFromBmrFragment.sex(BmrCalculation.SEX_MAN);
sexMan.setChecked(true);
sexWoman.setChecked(false);
break;
case R.id.sexWoman:
sexMan.setChecked(false);
sexWoman.setChecked(true);
mSendInfoFromBmrFragment.sex(BmrCalculation.SEX_WOMAN);
break;
Edit Text listener
#Override
public void afterTextChanged(Editable s) {
if ( s == weightEditText.getEditableText()){
mSendInfoFromBmrFragment.getweight(Integer.parseInt(s.toString()));
mWeight = Integer.parseInt(s.toString());
} else if ( s == heightEditText.getEditableText()) {
mSendInfoFromBmrFragment.getheight(Integer.parseInt(s.toString()));
mHeight = Integer.parseInt(s.toString());
} else if ( s == ageEditText.getEditableText()){
mSendInfoFromBmrFragment.getage(Integer.parseInt(s.toString()));
mAge = Integer.parseInt(s.toString());
}
if ( (!(weightEditText.getEditableText().toString().equals("")) && !(heightEditText.getEditableText().toString().equals("")) && !(ageEditText.getEditableText().toString().equals("")))) {
mSendInfoFromBmrFragment.editTextComplete(true);
} else {
mSendInfoFromBmrFragment.editTextComplete(false);
}
}
Interface
public interface sendInfoFromBmrFragment {
public void getheight(int height);
public void getweight(int weight);
public void getage(int age);
public void editTextComplete(boolean editTextComplete);
public void sex(String sex);
}
For the Radio Buttons you can declare an array if you know their number and they are static, do this as follow:
public Boolean AllRadiosAreChecked;
private Boolean Checked[] =
{
false, // sexMan is checked ?
false // sexWoman is checked ?
};
Then, in the same activity ovverride the OnCheckedChanged
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
switch (buttonView.getId()){
case R.id.sexMan:
Checked[0]=true;
break;
case R.id.sexWoman:
Checked[1]=true;
break;
Then you check anywhere you want if all Radio Buttons are checked:
AllRadiosAreChecked=true;
for (int i = 0; i < 2; i++)
{
if (!Checked[i])
{
AllRadiosAreChecked= false;
}
}
if(!AllRadiosAreChecked){
// NOT all radio buttons are checked
}
else{
// All radio buttons are checked enter code here
}
This conditions in the array must be declared to group radios.
Good Luck
You can add callbacks to your checkboxes and then they all are true you need call method in your parent activity (for example send in activity fragment ID and boolean value). To call method from activity you need to use the next code
((ParentActivity)getActivity()).yourMethod();
And then activity received all booleans from all fragment you need to change Button visibility.
If you have edittext you can add textchangelistener to it, if you have checkbox you can add listener of it, in listener you can check validation. Based on validation you can enable or disable the button for next activity. You can have that button to be static to access from other class.
In every listener you can call one public static method in which you will check all validation every time, if it satisfies then method will return true and you can enable button.
I have a checkbox. It is set to true or false depending on if a task is done or not (its a manual change). When the task is done I want the textview label to change frmo not done to done and vice versa. So I have the following code. When they click the checkbox the onCheckedChanged method does get fired off. It chooses sets the string depending on if it is true or false correctly. But then it just exits. I get no error in the logs or on the screen but when I step through the program after it sets the string in the onCheckedChanged method it just exits the getView method completely. I cant understand what is going wrong. Theres a small problem in the first couple lines that the logic for setting if the box is true or false is not entirely correct but thats fine I can fix that no problem. I just cant understand why I cant update the label after clickign the checkbox. Any help would be great.
final CheckBox statusView = (CheckBox)convertView.findViewById(R.id.statusCheckBox);
//statusView.setChecked(true);
if(toDoItem.getStatus().toString().compareTo(ToDoItem.Status.DONE.toString()) == 0)
statusView.setChecked(true);
else
statusView.setChecked(false);
// TODO - Must also set up an OnCheckedChangeListener,
// which is called when the user toggles the status checkbox
statusView
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i(TAG,"Entered onCheckedChanged()");
if(isChecked)
statusLabelValue = "Done";
else
statusLabelValue = "Not Done";
}
});
TextView statusLabel = (TextView)convertView.findViewById(R.id.StatusLabel);
statusLabel.setText(statusLabelValue);
You will have to change the textview's text in the listener:
statusView
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i(TAG,"Entered onCheckedChanged()");
if(isChecked)
statusLabelValue = "Done";
else
statusLabelValue = "Not Done";
((TextView)(convertView.findViewById(R.id.StatusLabel))).setText(statusLabelValue);
}
});
since i am trying the switch first time (new to android) i am not sure how to handle this issue. i have a switch on an activity and an attached setOnCheckedChangeListener() to it. when the activity's oncreate is called i make an async call to database and depending on the values received i set the status of the switch on/off. Now the problem is that however i am setting the switch state to just show whats its current status on db and no user has changed it yet, still the listner function is called. i know that the code is working correctly but with the state changed listner i need something else to confirm that the state has been changed by the user . i think onTouchEvent(MotionEvent event) can fill the purpose but do not know hot to use it in conjuction with switch.setOnCheckedChangeListener
does anyone know of any better solution to it or atleast can help me telling how to use ontouch even with listner...
sw_recording_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}}
thanks !!!
Indeed when calling Switch.setChecked(boolean); the OnCheckedChangeListener will be triggerd as well.
The way I overcame this problem was to use a flag and set it to false before I call setChecked()
This way the listener will still be called when you programmatically use setChecked() but the code inside won't execute, unless a user presses on the switch.
//prevent the code from listener to run, flag set to false before calling setChecked(true);
should_run = false;
toggle_facebook.setChecked(true);
....
private OnCheckedChangeListener onSwitchSlided = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
switch(buttonView.getId())
{
case R.id.settings_toggle_facebook:
{
if(true == should_run)
{
//do stuff
}
should_run = true;
break;
}
case R.id.settings_toggle_twitter:
{
if(true == should_run)
{
//do stuff
}
should_run = true;
break;
}
}
}
};
Two ways to handle initialization code so handlers do not fire.
Design your handler to recognize that it is initialization. Below example use isResumed() to determine if the code is initializing. This works because onCreate is called before onResume.
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
switch (rg.getId()) {
case R.id.rgMileKilometer:
switch (checkId) {
// process the speed radio group
case R.id.rdoMiles:
// Speed Radio Group check if the mph button is checked
isMile = true;
break;
case R.id.rdoKilometer:
isMile = false;
// Speed Radio Group check if the mph button is checked
break;
}
if (isResumed()) {
//do something the code is ready...
}
}
}
Add the listeners after you have done the initialization
CheckBox cb = (CheckBox) view
.findViewById(R.id.cbApplicationCacheTabs);
cb.setChecked(isApplicationCacheTabs);
cb.setOnCheckedChangeListener(this);
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"/>