【问题标题】:Android: Selector on custom View AttributeAndroid:自定义视图属性上的选择器
【发布时间】:2014-12-28 17:15:17
【问题描述】:

我已尝试遵循本指南: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>

【问题讨论】:

  • 行 final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);做什么?

标签: android layout


【解决方案1】:

你错过了refreshDrawableState 电话

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

来自文档

调用它来强制视图更新其可绘制状态。

【讨论】:

  • setToggle 在我的应用程序中从未被调用,它仅用于将来的代码。您的解决方案不起作用。
  • 您必须从构造函数中获取的 attrs 对象中读取自定义状态,设置布尔值并调用 refreshDrawableState
猜你喜欢
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多