SwitchCompat setTextOn() and setTextOff() doesn't work on runtime

时间:2017-08-05 12:20:32

标签: java android android-layout android-view switchcompat

I've tried to set the text on SwitchCompat, but it doesn't work. It only work for the first time. But when you tried to change the text (eg. when button is clicked), it doesn't work.

For example:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final SwitchCompat switchCompat = (SwitchCompat)findViewById(R.id.switch_test);
    switchCompat.setTextOn("Yes");
    switchCompat.setTextOff("No");
    switchCompat.setShowText(true);

    Button buttonTest = (Button)findViewById(R.id.button_test);
    buttonTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchCompat.setTextOn("YOO");
            switchCompat.setTextOff("NAH");
            //switchCompat.requestLayout();  //tried to this but has no effect
            //switchCompat.invalidate();     //tried to this but has no effect
        }
    });
}

You will see that the text stays as Yes and No. I've tried to call requestLayout() and invalidate() with no success. Any idea?

1 个答案:

答案 0 :(得分:4)

问题是,SwitchCompat的设计并非考虑到这种情况。它有私人字段mOnLayoutmOffLayout,在更改文本时会计算一次,not recomputed later

因此,您必须在文本更改的顺序中将它们显式为null,以启动要重新创建的布局。


    buttonTest.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        try {
          Field mOnLayout = SwitchCompat.class.getDeclaredField("mOnLayout");
          Field mOffLayout = SwitchCompat.class.getDeclaredField("mOffLayout");

          mOnLayout.setAccessible(true);
          mOffLayout.setAccessible(true);

          mOnLayout.set(switchCompat, null);
          mOffLayout.set(switchCompat, null);
        } catch (NoSuchFieldException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }

        switchCompat.setTextOn("YOO");
        switchCompat.setTextOff("NAH");

      }
    });

结果:

enter image description here