Android Switch setOnCheckedChangeListener方法通过应用DRY原则传递Object

时间:2016-07-21 15:11:59

标签: java android design-patterns dry

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) { }



        }
    });

请考虑以上代码。现在我有1个Switch这个代码片段就足够了。但是,如果我有4个开关,那么4次重复此代码片段。所以这是重复的。 这里为每个开关toggl1 - > msg =" 1&#34 ;; for toggl2 - > msg =" 2&#34 ;; 只是改变了每个地方。

如何将对象传递给 setOnCheckedChangeListener 以便我可以遵守DRY原则?

2 个答案:

答案 0 :(得分:1)

您可以使用View的标记,然后像这样检索

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);

buttonView传递的onCheckChanged是您切换的开关,它始终是您的切换变量之一

答案 1 :(得分:1)

创建自定义已检查的侦听器:

private class customChecked implements CompoundButton.OnCheckedChangeListener {

    String msg;
    public customChecked(String mMsg){
        this.msg= mMsg;
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        myString = msg;
    }
}

然后申请:

toggle1.setOnCheckedChangeListener(new customChecked(1));
toggle2.setOnCheckedChangeListener(new customChecked(2));