SwitchCompat setTextOn() 和 setTextOff() 在运行时不起作用

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

我试过在 SwitchCompat 上设置文本,但它不起作用。它只在第一次工作。但是当您尝试更改文本时(例如,当单击按钮时),它不起作用。

例如:

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

您会看到文本保持 YesNo。我尝试调用 requestLayout()invalidate() 但没有成功。有什么想法吗?

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

因此,您必须明确地将它们置空,以便文本更改以启动要重新创建的布局。


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

      }
    });

结果: