2009-10-07 2 views
98

기본 ToggleButton 모양을 덮어 쓰려고합니다. 여기에 ToggleButton 정의하는 XML입니다 : 이제Android : XML을 사용하여 토글 버튼에 두 가지 이미지 지정

<ToggleButton android:id="@+id/FollowAndCenterButton" 
     android:layout_width="30px" 
     android:layout_height="30px" 
     android:textOn="" android:textOff="" android:layout_alignParentLeft="true" 
     android:layout_marginLeft="5px" 
     android:layout_marginTop="5px" android:background="@drawable/locate_me"/> 

, 우리는 우리가 클릭/비 클릭 된 상태에 사용할 두 개의 30 X 30 아이콘이 있습니다. 지금은 상태에 따라 프로그래밍 방식으로 배경 아이콘을 변경하는 코드가 있습니다.

centeredOnLocation.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      if (centeredOnLocation.isChecked()) { 
       centeredOnLocation.setBackgroundDrawable(getResources().getDrawable(R.drawable.locate_me_on)); 
      } else { 
       centeredOnLocation.setBackgroundDrawable(getResources().getDrawable(R.drawable.locate_me)); 
      } 
     } 
}); 

분명히이 작업을 수행하는 더 좋은 방법을 찾고 있습니다. 나는 자동으로 상태 사이를 전환 할 배경 이미지에 대한 선택기 만들기 위해 노력했습니다 :

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/locate_me" /> <!-- default --> 
<item android:state_checked="true" 
     android:drawable="@drawable/locate_me_on" /> <!-- pressed --> 
<item android:state_checked="false" 
     android:drawable="@drawable/locate_me" /> <!-- unchecked --> 

을하지만이 작동하지 않습니다; 방법 isChecked()setChecked()을 갖는 클래스에도 불구하고, state_checked 속성 다음 ToggleButton API (http://developer.android.com/reference/android/widget/ToggleButton.html)를 읽고, 유일한 상속 XML 속성이

XML Attributes 
Attribute Name Related Method Description 
android:disabledAlpha  The alpha to apply to the indicator when disabled. 
android:textOff   The text for the button when it is not checked. 
android:textOn  The text for the button when it is checked. 

는 안드로이드 것 같다하지 않는 것으로 나타납니다.

XML에서 원하는 작업을 수행 할 수있는 방법이 있습니까? 아니면 어수선한 해결 방법을 고수하고 있습니까?

+0

참고로, 텍스트를 사용하지 않는다면 'CompoundButton'을 사용하는 것이 더 좋을 것 같습니다. – Timmmm

+1

무시하십시오. 'CompoundButton' 추상입니다! – Timmmm

답변

159

코드가 정상입니다. 그러나 토글 버튼은 일치하는 선택기의 첫 번째 항목을 표시하므로 기본값이 마지막에 오게됩니다. 다음과 같은 방법으로 항목을 배열하여 모두 활용되도록하십시오 :

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_checked="true" android:state_pressed="true" /> //currently pressed turning the toggle on 
    <item android:state_pressed="true" /> //currently pressed turning the toggle off 
    <item android:state_checked="true" /> //not pressed default checked state 
    <item /> //default non-pressed non-checked 
</selector> 
+3

그건 완벽하게 이해할 수 있습니다. 나는 selector와 switch 문을 연결하지 않았다. – I82Much

+0

당신은 나의 하루를 보냈습니다 ... 버튼, 체크 박스에 문제가 있었고 라디오 버튼도 시도했습니다. 마침내이 게시물은 도움이되었습니다. Vitaly Polonetsky와 I82Much –

+0

정말 감사합니다. 고마워. – anticafe

관련 문제