2015-01-16 3 views
0

내 안드로이드 액티비티에는 두 개의 Switch 버튼이 있습니다.
둘 다 사용자 정의 동적 On/Off 텍스트 (런타임시 Switch.setTextOn(CharSeq)으로 설정 됨)가 있습니다.
그들은이 (다른 SO 스레드에서 발견 이미지)처럼 :
custom switch text
제 1 스위치의 온/오프 텍스트를 한 번 설정됩니다.여러 Switch.setTextOn() 스위치의 텍스트를 업데이트하지 않습니다.

제 목표는 첫 번째 스위치의 상태가 변경되었을 때 두 번째 스위치의 온/오프 텍스트를 동적으로 수정하는 것입니다.

그래서 나는이 같은 제 1 스위치에 OnCheckedChangeListener을 설정 :

switch2.setTextOff("ImOff"); // works, the text is updated on the switch 

switch2.setTextOn("ImOn"); // same here 

switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if(!isChecked) 
       { 
        switch2.setTextOff(myStrings.get(2)); 
        switch2.setTextOn(myStrings.get(3)); // here switch2.getTextOn() returns the value of myStrings.get(3), but the widget still displays ImOn... 
       } else 
       { 
        switch2.setTextOff(myStrings.get(4)); 
        switch2.setTextOn(myStrings.get(5)); // here switch2.getTextOn() returns the value of myStrings.get(5), but the widget still displays ImOn... 
       } 
       // I tried to update the switch with this and this 
       switch2.invalidate(); 
       switch2.setChecked(valuesSwitch.isChecked()); 
      } 
     }); 

하지만이 코드는 제 2 스위치의 온/오프 텍스트에 개체에 설정되어 작동하지 않습니다 (getTextOn/Off 오른쪽 텍스트를 반환합니다). 그러나 위젯은 여전히 ​​초기 텍스트 ImOn/ImOff를 표시합니다 ...

아이디어가 있습니까? 감사. I이 링크에서 솔루션을 발견

답변

1

(스위치 연장) 파생 클래스

https://groups.google.com/forum/#!topic/android-developers/1IYypcoYXlk

, 이하의 방법 재정의

Override 
public void request layout() { 
    try { 
     java.lang.reflect.Field mOnLayout = Switch.class.getDeclaredField ("mOnLayout"); 
     mOnLayout.setAccessible (true); 
     mOnLayout.set (this, null); 
     java.lang.reflect.Field mOffLayout = Switch.class.getDeclaredField ("mOffLayout"); 
     mOffLayout.setAccessible (true) ; 
     mOffLayout.set (this, null); 
    } Catch (Exception ex) { 
     Log.e (TAG, ex.getMessage(), ex); 
    } 
    super.requestLayout(); 
} 
관련 문제