Próbuję zastąpić domyślny wygląd ToggleButton
. Oto XML, który definiuje ToggleButton
:Android: Określ dwa różne obrazy dla togglebutton przy użyciu 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"/>
Teraz mamy dwa 30 x 30 ikony chcemy wykorzystać dla kliknęli/państwa niebędącego kliknięciu. W tej chwili mamy kod, który programowo zmienia ikonę tła w zależności od stanu:
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));
}
}
});
Oczywiście szukam lepszego sposobu na zrobienie tego. Próbowałem dokonać wyboru dla obrazu tła, który automatycznie przełącza pomiędzy stanami:
<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 -->
Ale to nie działa; czytanie ToggleButton
API (http://developer.android.com/reference/android/widget/ToggleButton.html), wydaje się, że jedynymi odziedziczone atrybuty XML są
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.
Nie wydaje się być android: state_checked atrybut, mimo klasa ma metodę isChecked()
i setChecked()
.
Czy istnieje sposób, aby zrobić to, co chcę w XML, czy utknąłem z moim niechlujnym obejściem?
Uwaga, jeśli nie używasz tekstu, myślę, że lepiej użyć "CompoundButton". – Timmmm
Zignoruj to; "CompoundButton" jest abstrakcyjny! – Timmmm