自定义按钮具有自定义状态

时间:2015-04-16 13:41:16

标签: android

我创建了一个自定义按钮类(我遵循了这个主题:http://developer.android.com/training/custom-views/create-view.html

现在我想创建一个自定义状态(state_avaibility),我创建了一个新的attribut attrs.xml:

<declare-styleable name="CustomButton">
    <attr name="state_available" format="boolean" />
</declare-styleable>

我想用

 StateListDrawable mNormalDrawable;
 mNormalDrawable = new StateListDrawable();
 mNormalDrawable.addState(new int[]{R.attr.state_available}, createAvailableDrawable(attr));

但是这种方法不接受自定义状态。

您知道如何创建自定义按钮(以编程方式创建)并添加自定义状态?

编辑:

我创建了两个按钮(可用且不可用),我有两种方法可以做到:

private LayerDrawable createAvailableDrawable(TypedArray attr) {
LayerDrawable drawableAvailable = (LayerDrawable) getDrawable(R.drawable.button_available).mutate();

// Some modifications with custom attributs
   return drawableAvailable;
}

private LayerDrawable createUnavailableDrawable(TypedArray attr) {
LayerDrawable drawableUnavailable = (LayerDrawable) getDrawable(R.drawable.button_unavailable).mutate();

// Some modifications with custom attributes 
   return drawableUnavailable;
}

我有一个新的自定义属性后:

<declare-styleable name="CustomButton">
    <attr name="state_available" format="boolean" />
</declare-styleable>

然后我覆盖onCreateDrawableState方法:

@Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);

        if (mIsAvailable) {
            mergeDrawableStates(drawableState, STATE_AVAILABLE);
        }

        return drawableState;
    } 

然后我尝试了这个:

 StateListDrawable mNormalDrawable;
 mNormalDrawable = new StateListDrawable();
 mNormalDrawable.addState(new int[]{R.attr.state_available}, createAvailableDrawable(attr));
mNormalDrawable.addState(new int[]{-R.attr.state_available}, createUnavailableDrawable(attr));

现在我添加按钮:

<mobile.custom.com.library.Widget.CustomButton
        android:id="@+id/CustomButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        custom:vd_cornerRadius="5dp"
        custom:vd_color_text_unavailable="@color/yellow"
        custom:vd_text_available="@string/available"
        custom:vd_text_unavailable="@string/unavailable"
        custom:state_available="false" />

现在,当我更改custom:state_available的值时,按钮不会更改

1 个答案:

答案 0 :(得分:0)

在您的CustomButton,类覆盖onCreateDrawableState中,合并您的自定义状态:

private static final int[] STATE_AVAILABLE = { R.attr.state_available };

@Override
public int[] onCreateDrawableState(int extraSpace) {
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
    if (available) {
        mergeDrawableStates(drawableState, STATE_AVAILABLE);
    }
    return drawableState;
}

mergeDrawableStates会将您的自定义状态STATE_AVAILABLE合并到基本状态