100

ToggleButtonデフォルトの外観を上書きしようとしています。ToggleButtonこれが:を定義する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"/>

これで、クリック/非クリック状態に使用する2つの30x30アイコンができました。現在、状態に応じて背景アイコンをプログラムで変更するコードがあります。

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属性は

    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()クラスにメソッドとが含まれているにもかかわらず、android:state_checked属性がないようですsetChecked()

それで、私がXMLでやりたいことをする方法はありますか、それとも私は厄介な回避策で立ち往生していますか?

4

1 に答える 1

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>
于 2009-10-07T18:37:27.310 に答える