3

假设 anattraar包 ( com.pack1) 中定义为

<attr name="attr0" format="string" />

在另一个包中(比如com.pack2依赖于com.pack1)我定义styleable

<attr name="attr2" format="integer" />
<declare-styleable name="view2">
    <attr name="attr1" format="string" />
    <attr name="attr2" />
</declare-styleable>

我有一个自定义com.pack2视图

public class View2 extends LinearLayout
{
    public View2(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);
        View.inflate(context, R.layout.view2, this);
        try
        {
            TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.view2);
            {
                if (typedArray.hasValue(R.styleable.view2_attr1))
                {
                    String t = typedArray.getString(R.styleable.view2_attr1);
                    logger.debug("attr1 -> has value -> {}", t);
                }
                else
                    logger.debug("attr1 -> no value");
                if (typedArray.hasValue(R.styleable.view2_attr2))
                {
                    int t = typedArray.getInteger(R.styleable.view2_attr2, 0);
                    logger.debug("attr2 -> has value -> {}", t);
                }
                else
                    logger.debug("attr2 -> no value");
            }
            typedArray.recycle();
        }
        catch (Throwable t)
        {
            logger.debug(t.toString());
        }
    }
}

我将自定义视图添加到布局中

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.pack2.View2
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        custom:attr1="this is a test"
        custom:attr2="1000"
        />

</LinearLayout>

到这里,当我运行应用程序时一切正常,记录器报告说

attr1 -> has value -> this is a test
attr2 -> has value -> 1000

但只要我改变styleableas

<attr name="attr2" format="integer" />
<declare-styleable name="view2">
    <attr name="attr0" />
    <attr name="attr1" format="string" />
    <attr name="attr2" />
</declare-styleable>

并运行我收到错误结果的应用程序。记录器报告说

attr1 -> no value

并且发生了异常

java.lang.UnsupportedOperationException: Can't convert to integer: type=0x3

听起来“这是一个测试”的值已被消耗,attr0尽管该属性未在布局中定义。请注意,应用程序编译正确,但结果错误。

为什么我会收到这个结果?

4

0 回答 0