jeudi 21 juillet 2016

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 ?

Aucun commentaire:

Enregistrer un commentaire