2017-08-05 21 views
1

我試圖設置SwitchCompat上的文本,但它不起作用。它只是第一次工作。但是,當你試圖改變文本(例如,當按鈕被點擊),它不起作用。SwitchCompat setTextOn()和setTextOff()在運行時不起作用

例如:

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

你會看到這些內容一直爲沒有。我試圖撥打requestLayout()invalidate()沒有成功。任何想法?

回答

4

問題是,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"); 

     } 
    }); 
 

結果:

enter image description here

+1

很好的解決方案!我發佈了相同的答案,但你先來:) –

+1

誰是我的男人?誰是我的男人!?!? Azizbekian是我的男人!感謝隊友,它的工作! – Sam

相關問題