3

Assume an attr is defined in aar package (com.pack1) as

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

and in another package (say com.pack2 which has dependency on com.pack1) I define an styleable as

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

and I have a custom view in com.pack2 as

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());
        }
    }
}

And I add the custom view to a layout as

<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>

Up to here when I run the app everything works fine and the logger reports that

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

but as soon as I change the styleable as

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

and run the app I receive wrong results. The logger reports that

attr1 -> no value

and an exception occurred

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

It sounds like the value "This is a test" is consumed for attr0 although that attribute is not defined in layout. Note that app gets compiled correctly but the result is wrong.

Why do I receive that result?

anonim
  • 2,494
  • 6
  • 30
  • 40

0 Answers0