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

Nik*_*hil 8 java android custom-component

我为我的Android应用程序创建了自定义小部件,我想为它创建自定义样式.但是在类中解析它时总是返回null.通过几个链接,无法弄清楚问题是什么?有人可以帮忙吗?

我的atttr.xml是

<resources>

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

</resources>
Run Code Online (Sandbox Code Playgroud)

小部件类

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);
}    
Run Code Online (Sandbox Code Playgroud)

和布局文件

<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>
Run Code Online (Sandbox Code Playgroud)

Arrays.xml是

<resources>

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

</resources>
Run Code Online (Sandbox Code Playgroud)

Nik*_*hil 0

在检查了几个样本后,我发现了问题所在。

刚换了线

TypedArray attr = context.obtainStyledAttributes(attrs,
        R.styleable.Widget);
Run Code Online (Sandbox Code Playgroud)

有了这个

TypedArray attr = context.getTheme().obtainStyledAttributes(attrs,
        R.styleable.Widget,0,0)
Run Code Online (Sandbox Code Playgroud)