Android解析自定义小部件样式不起作用

8

我已经为我的安卓应用程序创建了自定义小部件,现在我想为它创建自定义样式。但是在类中解析时总是返回null。查阅了几个链接,仍然无法找出问题所在。有人可以帮忙吗?

我的atttr.xml文件如下:

<resources>

    <declare-styleable name="Widget">
        <attr name="headers" format="reference" />
        <attr name="height" format="integer" />
    </declare-styleable>

</resources>

部件类

public Widget(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray attr = context.obtainStyledAttributes(attrs,
            R.styleable.Widget);
    String[] columns = (String[]) attr
            .getTextArray(R.styleable.Widget_headers);

    int height = attr.getInt(R.styleable.Widget_height, 0);
}    

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:widget="http://schemas.android.com/apk/lib/com.sample.custom"
    android:id="@+id/statistics_fragment_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.sample.custom.Widget
        android:id="@+id/widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        widget:headers="@array/headers" >
    </com.sample.custom.Widget>
</LinearLayout>

Arrays.xml is

<resources>

    <string-array name="headers">
        <item>Header1</item>
        <item>Header2</item>
        <item>Header3</item>
    </string-array>

</resources>
2个回答

1

你是否尝试在视图构造函数结尾处回收数组?这个链接涵盖了大部分内容 - 创建自定义视图


0

经过查看几个示例,我找到了问题所在。

只需替换该行即可

TypedArray attr = context.obtainStyledAttributes(attrs,
        R.styleable.Widget);

使用这个

TypedArray attr = context.getTheme().obtainStyledAttributes(attrs,
        R.styleable.Widget,0,0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接