Saiful Islam Saiful Islam - 4 months ago 9
Java Question

Android DRY for Switch setOnCheckedChangeListener method to pass Object

toggle1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

try
{
String msg ="";
if (isChecked) {
// The toggle is enabled

//msg = "Hello " + String.valueOf(!isChecked);
msg = "1";


} else {
// The toggle is disabled
//msg = "Hello " + String.valueOf(!isChecked);
msg = "1";
}
msg += "\n";
outputStream.write(msg.getBytes());

}
catch (IOException ex) { }
catch (NullPointerException ex) { }



}
});


Please consider the above code. Now I have 1 Switch so one this code snippet. If I have 4 so 4 times repeat this code snippet. So this is duplicate.
Here for toggl1 ->msg = "1"; for toggl2 ->msg = "2"; Just this change each place.

How I can pass object to setOnCheckedChangeListener so that I can obey DRY principle ?

Answer

You can use the tag of the View and retrieve it later like this

CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        try {
            String msg ="";
            if (isChecked) {
                // The toggle is enabled

                //msg = "Hello " + String.valueOf(!isChecked);
                msg = buttonView.getTag().toString()


            } else {
                // The toggle is disabled
                //msg = "Hello " + String.valueOf(!isChecked);
                msg = buttonView.getTag().toString()
            }
            msg += "\n";
            outputStream.write(msg.getBytes());

        } catch (IOException ex) {

        }
        catch (NullPointerException ex) {

        }
    }
};

toggle1.setTag("1");
toggle2.setTag("2");
toggle3.setTag("3");

toggle1.setOnCheckedChangeListener(listener);
toggle2.setOnCheckedChangeListener(listener);
toggle3.setOnCheckedChangeListener(listener);

The buttonView passed by onCheckChanged is the switch you toggled, which is always one of your toggle variables