2

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?

Turner Hayes
  • 1,844
  • 4
  • 24
  • 38

2 Answers2

2

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.

Turner Hayes
  • 1,844
  • 4
  • 24
  • 38
0

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>
dcanh121
  • 4,665
  • 11
  • 37
  • 84
  • Yeah, sorry, I forgot about that part. I've added it to the OP. I didn't include a header ID as an integer type, I included a header as a reference type. – Turner Hayes Aug 30 '11 at 18:00