簡體   English   中英

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 ,它們僅計算一次, 以后在更改文本時不會重新計算

因此,您必須明確地使它們無效,以便更改文本以啟動要重新創建的布局。


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

      }
    });

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM