1

我尝试按照本指南这篇关于如何为自定义视图的布局 XML 制作自定义属性的帖子,但是无论我做什么,我都会返回一个零自定义属性列表,而且我在计算时遇到了很多麻烦出如何调试这个。

我制作了一个文件 res/values/attrs.xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TexturedListView">
        <attr name="backgroundTexture" format="reference"/>
    </declare-styleable>
</resources>

然后我在布局 XML 文件中创建了一个自定义视图,如下所示:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res/xxx.rtin.texturedlistview"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <xxx.rtin.texturedlistview.TexturedListView
        android:id="@+id/texturedListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:dividerHeight="10dp"
        android:padding="20dp"
        custom:backgroundTexture="@drawable/background" >
    </xxx.rtin.texturedlistview.TexturedListView>

</RelativeLayout>

然后从我的 TexturedListView 类的构造函数中,我调用以下内容来尝试读取此自定义属性:

public TexturedListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(R.styleable.TexturedListView);

    final int N = a.getIndexCount();
    //..snip...
}

然而,毫无疑问,N 是 0。 R.styleable.TexturedListView 似乎有正确的 ID,我尝试清理和重建我的项目,但无济于事。我觉得我必须错过一些微妙的东西,但我无法弄清楚。

我究竟做错了什么?如何阅读这些自定义属性?

4

0 回答 0