多个Switch.setTextOn()不更新switch的文本

时间:2015-01-16 14:29:13

标签: android uiswitch

我的Android Activity中有两个Switch个按钮 两者都有自定义动态开/关文本(在运行时使用Switch.setTextOn(CharSeq)设置) 它们看起来像这样(在另一个SO线程上找到的图像):
 custom switch text
第一个开关的开/关文本设置一次。

我的目标是在第一个开关的状态发生变化时动态修改第二个开关的开/关文本。

所以我在第一个开关上设置OnCheckedChangeListener,如下所示:

 switch2.setTextOff("ImOff");  // works, the text is updated on the switch

 switch2.setTextOn("ImOn"); // same here

 switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(!isChecked)
                {
                   switch2.setTextOff(myStrings.get(2));  
                   switch2.setTextOn(myStrings.get(3));  // here switch2.getTextOn() returns the value of myStrings.get(3), but the widget still displays ImOn...
                } else
                {
                   switch2.setTextOff(myStrings.get(4));  
                   switch2.setTextOn(myStrings.get(5)); // here switch2.getTextOn() returns the value of myStrings.get(5), but the widget still displays ImOn...
                }
                // I tried to update the switch with this and this
                switch2.invalidate();
                switch2.setChecked(valuesSwitch.isChecked());
            }
        });

但是这段代码不起作用,第二个开关的开/关文本在对象上设置(getTextOn/Off返回正确的文本),但小部件仍然显示初始文本ImOn / ImOff ...

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

我在这个链接中找到了一个解决方案,

https://groups.google.com/forum/#!topic/android-developers/1IYypcoYXlk

在派生类(其中扩展switch)中,重写以下方法:

Override
public void request layout () {
    try {
        java.lang.reflect.Field mOnLayout = Switch.class.getDeclaredField ( "mOnLayout");
        mOnLayout.setAccessible (true);
        mOnLayout.set (this, null);
        java.lang.reflect.Field mOffLayout = Switch.class.getDeclaredField ( "mOffLayout");
        mOffLayout.setAccessible (true) ;
        mOffLayout.set (this, null);
    } Catch (Exception ex) {
        Log.e (TAG, ex.getMessage (), ex);
    }
    super.requestLayout ();
}