I have this code here
ToggleButton toggleAlarm = (ToggleButton) d.findViewById(R.id.toggle_alarm);
toggleAlarm.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
Log.d("alarmCheck","ALARM SET TO TRUE");
sched.setAlarm(true);
}
else
{
Log.d("alarmCheck","ALARM SET TO FALSE");
sched.setAlarm(false);
}
}
});
I have to keep track if its ON or OFF. But when I logged something to logcat where it is on or off, it won't do a thing. I don't know, what is wrong, because on my other code same, syntax but it works I just copy paste it and change only the ToggleButton variable.
EDIT
I have observed, with the help of cdr. Powell of course, that when you put this code block, the one that I have posted, inside another anonymous listener, say listener for a save button, the checkOnChangedListener is broken, it doesn't function well inside another anonymous listener, but the one thing that I don't understand is that, there is also a outer listener in my code, it is like a button to display a dialog box and inside that dialog box, there is an add button that opens another dialog box which has that toggle button and another button for save or add which closes that dialog and returns to the previous dialog which will then display the newly added record, so anyone of you have an idea why is it broken when i put it inside a listener for a save button but works fine in a outer listener.
try this, May be the problem is with import
toggleAlarm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
Log.d("alarmCheck","ALARM SET TO TRUE");
sched.setAlarm(true);
}
else
{
Log.d("alarmCheck","ALARM SET TO FALSE");
sched.setAlarm(false);
}
}
});
Try toggleAlarm.isChecked() too see if the button is checked or not.
In case toggleAlarm.isChecked() does not work for you you could always.
boolean _isChecked = false;
((ToggleButton) d.findViewById(R.id.toggle_alarm)).setOnClickListener(new OnOnClickListener() {
public void onClick(View arg0) {
_isChecked = !isChecked;
if(_isChecked()) {
Log.d("alarmCheck","ALARM SET TO TRUE");
sched.setAlarm(true);
}
else {
Log.d("alarmCheck","ALARM SET TO FALSE");
sched.setAlarm(false);
}
}
});
So i have observed, with the help of cdr. powell of course, that when u put this code block, the one that i have posted, inside another anonymous listener, say listener for a save button, the checkOnChangedListener is broken, it doesn't function well inside another anonymous listener, but the one thing that i don't understand is that, there is also a outer listener in my code, its like a button to display a dialog box and inside that dialog box, there is an add button that opens another dialog box which has that toggle button and another button for save or add which closes that dialog and returns to the previous dialog which will then display the newly added record, so anyone of you have an idea why is it broken when i put it inside a listener for a save button but works fine in a outer listener.
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
}
So I'm working on a list of check boxes. I'm using the OnClickListener to catch the touch event. I've also tried the OnTouch listener and the OnCheckChanged listener. The issue I've come across is the fact that the check box IsChecked value is set to true before it reaches any of these event listeners. So if I were to do something like this:
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkBox.isChecked())
checkBox.setChecked(false);
}
});
It will always hit this if statement and immediately set the checkbox to unchecked because it's setting it as ischecked true before it reaches OnClickListener. The easiest way around this I've found is:
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkBox.setChecked(!checkBox.isChecked());
if (checkBox.isChecked()) {
checkBox.setChecked(false);
}
}
});
But this is what I would call hackish. The other option I see being to create a new checkbox class and override the preformClick method.
#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;
}
But that seems like a lot more work than should need to go in to accomplishing this task.
So, essentially my question is: Is there a method where I can override and intercept the setting of the checkbox before it is actually changed?
The OnClickListener of the CheckBox always gets called after it changed its checked state (as you can see in the performClick() method you copied, the toggle() method changes the checked state, before calling super's performClick(), which will call the OnClickListener).
If you don't want to always change the checked state of the CheckBox, then you can override performClick() and leave out the toggle() method (or only call it if some condition is true).
But if you want to change the state every time a click happens, then the easiest way is to use the OnClickListener, and just negate your conditions (e.g. if you want to do something when the checkbox was empty, then you check if the checkbox's new state is not empty).
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 have to two Class in my App
Setting(for saving the settings)
main Class
I defined the Toggle button and check box in Setting class for On and Off.
now when I call the setting class and from the main class and the change the checked state of Toggle Button and Check Box and the return to main class and if I again call the Setting class the checked state of the Toggle button and check box is not change it come back to it original state please help
My CODE:
yes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(((CheckBox) v).isChecked())
sound.toggle();
}
});
sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Log.v("CheckBoxActivity", (isChecked ? "checked" : "not checked"));
}
});
}
public void doClick(View view) {
Log.v("CheckBoxActivity", ((CheckBox) view).isChecked() ? "checked" : "not checked");
}
This probably will be the problem as each time your activity starts,it would take default selection state for the components.
To achieve you goal,you need to store what state you need for a toggle button and checkbox.And then you will have to set the according state of the same each time you load activity,that mean in onCreate() just before you start defining onClick() on those components.
You can use SharedPreference object to store state at a time and use the same in onCreate() of you activity to set stored states of toggle button and checkboxes.
There are a lot of options on how to define a click/tap on the touchscreen. One of them for example is setting a boolean.
Example for boolean:
boolean buttonClicked = true;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (buttonClicked) {
//do that and this
}
}
});
And there's a isPressed() method:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (button.isPressed()) {
//do that and this
}
}
});
What exactly is the difference between them? And when and why do I use boolean and the method isPressed()?
Because you are referring to a button in both of your examples, I assume that you are referring to the user tapping on a button, not just a random touch on the screen.
That being said, both of the examples you provided are not good.
In your first example, the boolean is useless because it is always true, so //do that and this will always be reached.
In your second example, your if statement is useless, because the onClick method by its nature is only reached when the button is tapped.
A good way to listen for a button press is using a click listener like this:
Button button = (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Code placed here will run every time the button is tapped
}
});
...where R.id.buttonId is the ID of your button in the layout.
If you need to define click event for a View you can use onClickListener, onTouchListener.
For more information check for Android official Documentation.
onTouchListener
onTouchListener
When considering your first code snippet, You can use boolean to perform another operation on button click event. as example something like this ,
boolean buttonClicked = false;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//true after button clicked
buttonClicked = true;
}
});
//if buttonClicked equals true
if (buttonClicked){
//perform operation only after button clicked
}
when considering your second code snippet, no need of button.isPressed() inside
button's onClick() callback. Because what you want to do by checking button.isPressed() is done without it inside button's onClick() callback.
Keep in mind these things.
isPressed() is a public method of View Class
Button is a subclass of View Class
isPressed() is a public method of Button Class as well.
About isPressed() from Android official documentation.
Indicates whether the view is currently in pressed state. Unless
setPressed(boolean) is explicitly called, only clickable views can
enter the pressed state.
Returns true if the view is currently pressed, false otherwise.