반응형
Android : 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 아이콘이 있습니다. 현재 상태에 따라 배경 아이콘을 프로그래밍 방식으로 변경하는 코드가 있습니다.
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 -->
그러나 이것은 작동하지 않습니다. 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.
클래스에 메소드 isChecked()
및 .NET Framework가 있음에도 불구하고 android : state_checked 속성이없는 것 같습니다 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>
반응형
'IT story' 카테고리의 다른 글
Git : 전체 git 히스토리에 대해 지정된 파일의 한 줄에 대한 다양한 변경 사항을 모두 표시합니다. (0) | 2020.08.20 |
---|---|
OpenJDK와 AdoptOpenJDK의 차이점 (0) | 2020.08.20 |
WPF ColumnDefinition에서 * (별표)의 의미? (0) | 2020.08.20 |
파이썬에서 hash (n) == n은 언제입니까? (0) | 2020.08.20 |
TensorFlow, 모델을 저장 한 후 3 개의 파일이있는 이유는 무엇입니까? (0) | 2020.08.20 |