sourcecode

안드로이드:XML을 사용하여 전환 단추에 대해 두 개의 다른 이미지 지정

copyscript 2022. 9. 3. 13:29
반응형

안드로이드:XML을 사용하여 전환 단추에 대해 두 개의 다른 이미지 지정

디폴트를 덮어쓰려고 합니다.ToggleButton외모.다음 XML은 다음을 정의합니다.ToggleButton:

<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 아이콘이 2개 있습니다.현재 상태에 따라 프로그램 방식으로 배경 아이콘을 변경하는 코드가 있습니다.

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 -->

그러나 이것은 동작하지 않습니다.ToggleButtonAPI(http://developer.android.com/reference/android/widget/ToggleButton.html), 상속된 xml Atribute는 다음과 같습니다.

    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. 

클래스에 메서드가 있는데도 Android:state_checked 속성이 없는 것 같습니다.isChecked()그리고.setChecked().

XML로 원하는 것을 할 수 있는 방법이 있을까요?아니면 복잡한 회피책에 시달리고 있는 걸까요?

네 코드는 괜찮아.단, 토글버튼에는 일치하는 셀렉터의 첫 번째 항목이 표시되므로 기본값은 마지막에 표시됩니다.모든 항목을 사용할 수 있도록 다음 방법으로 항목을 배열합니다.

<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>

언급URL : https://stackoverflow.com/questions/1533038/android-specify-two-different-images-for-togglebutton-using-xml

반응형