Android:自定义视图属性上的选择器

时间:2014-11-01 15:18:28

标签: android layout

我试图通过以下指南:How to add a custom button state来创建自己的视图属性,并使用选择器来更改其状态。 我似乎无法让它发挥作用。按钮选择器在非自定义选择器上工作正常,例如按下按钮,但对我的服务器选择器不起作用。 我的代码如下:

在attrs.xml中:

<resources>
    <declare-styleable name="ValueButton">
        <attr name="toggle" format="boolean" />
    </declare-styleable>
</resources>

在我的自定义按钮类定义文件中,名为ValueButton.java:

public class ValueButton extends Button
{
    private static final int[] STATE_TOGLLE = {R.attr.toggle};
    private boolean toggle = false;

    public void setToggle(boolean val)
    {
        toggle = val;
    }

    public ValueButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
        if(toggle)
            mergeDrawableStates(drawableState,STATE_TOGLLE);
        return drawableState;
    }
}

在我看来使用按钮:

<LiniarLayout>
    <com.myapp.ValueButton
            android:id="@+id/rightText"
            custom:toggle="false"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            style="@style/ValueSwitchStyle"
     />
</LiniarLayout>

在我的styles.xml文件中:

<style name="ValueSwitchStyle">
     <item name="android:background">@drawable/value_switch_background</item>
</style>

最后是我的后台定义文件(button_background.xml),位于drawables文件夹中:

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/com.myapp.ValueButton">
    <item custom:toggle="true" android:drawable="@color/blue"/>
    <item custom:toggle="false" android:drawable="@color/white"/>
</selector>

1 个答案:

答案 0 :(得分:1)

您错过了refreshDrawableState来电

public void setToggle(boolean val) {
        toggle = val;
        refreshDrawableState();
}

来自文档

  

调用此方法强制视图更新其可绘制状态。