【问题标题】:SwitchCompat setTextOn() and setTextOff() doesn't work on runtimeSwitchCompat setTextOn() 和 setTextOff() 在运行时不起作用
【发布时间】:2017-08-05 12:20:32
【问题描述】:

我尝试在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(),但没有成功。有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    问题是,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"); } });

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 2021-06-12
      相关资源
      最近更新 更多