Вопрос

I'm trying to create a control (a panel that expands and contracts when a header is clicked), and I found some code online. In the constructor, I have

TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyControl);
...
int headerId = array.getResourceId(R.styleable.MyControl_header, -1);

The control is being created in a layout file with the following XML:

<MyControl
        android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
        header="@+id/header" content="@+id/drawerContent"
        android:layout_below="@id/contentContainer" android:background="#00FF00">
    <TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@id/header"
            android:text="This is a header"/>

    <TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@id/drawerContent"
            android:text="@string/sample_text" />
</MyControl>

The problem is, getResourceId() comes back with -1 (i.e., it can't seem to find the resource set to the attribute).

Any idea why?

EDIT: Forgot to include my attrs.xml file:

<resources>
<declare-styleable name="MyControl">
    <attr name="collapsedHeight" format="dimension" />
    <attr name="header" format="reference" />
    <attr name="content" format="reference" />
    <attr name="animationDuration" format="integer" />
</declare-styleable>

EDIT 2: Somehow, I didn't think to check the other attributes--there were a couple of other attributes I had added. I checked their values in the debugger, too, and it looks like they're defaulting, as well. So it's not an issue with getResourceId, it's something to do with how I'm getting the attributes in general. I'm new to Android, so can anyone see anything in my attribute processing code?

Это было полезно?

Решение

Figured it out. It turns out, the attributes have to be namespaced in the XML; I put

<MyControl
    android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
    header="@+id/header" content="@+id/drawerContent"...

but it needed to be

<MyControl xmlns:myPackage="http://schemas.android.com/apk/res/com.my.package"
    android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/drawer"
    myPackage:header="@+id/header" myPackage:content="@+id/drawerContent"

After I added those, it found the values just fine.

Другие советы

Did you add the resources in values-> attrs.xml file?

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyControl">
    <attr name="headerId" format="integer" />
    </declare-styleable>
</resources>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top