-2

I have a Switch. It works like this 1. Turn it ON shows you AlertDialog with Download/locate/cancel options to perform (download)/(locate locally)/(cancel the dialog)

2.Turn it OFF shows you AlertDialog with Yes/No options to delete the files

Now Assume initially, the Switch state is OFF. Now if I turn it ON, Listener will register OnChecked as true. Next, if I press cancel the Dialog, OnChecked will be set to false, since no files were located/downloaded. Now this change is detected by the listener even though it is set programmatically. I need a way to divide Switch state Changes caused by user and program.

My listener is OnCheckedChangeListener.

I know there are similar questions having solutions online which are either makeshift or incomplete.

EDIT: I edited and changed the complete structure of the question to address my root objective. It shouldn't be a problem since there are no answers by the time of this edit.

1 Answers1

0

There are several answers online for this issue. They include writing Custom Switches extending SwitchCompat, CompundButton etc; with a SilentlySetChecked method.

If instead of OnCheckedChangeListener, if we implement the OnClickListener, there will not be any recursion of alert dialog's issue. But we cannot detect Swipe changes in this listener.

Simply, we need to detect State Changes done by clicking/swiping without recursion issue:

    CompoundButton.OnCheckedChangeListener downloadButtonListener = new CompoundButton.OnCheckedChangeListener() { 
@Override 
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
if (holder.downloadSwitch.isPressed() & isChecked) {
//if switch is turned on by click/swipe
}
else if(holder.downloadSwitch.isPressed() & !isChecked{
//if switch is turned on by click/swipe
}
}
});

This is a simple enough solution that solves the issue. But, It never came up on search, except partially here. Let me know if there is a better solution that I am missing.

NOTE: I posted this as a solution since it also answers the edited question. I will wait for few days for better answers before accepting my own as the solution.

Community
  • 1
  • 1