我试图在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
        }
    });
}


您将看到该文本保留为Yes和No。我尝试调用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"); } });


结果:

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

10-05 17:55