【问题标题】:Android parsing styles for custom widget not working自定义小部件的Android解析样式不起作用
【发布时间】:2014-02-23 18:09:17
【问题描述】:

我为我的 android 应用程序创建了自定义小部件,我想为它创建自定义样式。但是在类中解析它时总是返回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 是

<resources>

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

</resources>

【问题讨论】:

    标签: java android custom-component


    【解决方案1】:

    您是否尝试在视图构造函数的末尾回收数组?此链接涵盖了大部分内容 - creating custom views

    【讨论】:

      【解决方案2】:

      经过几个示例后,我发现了问题所在。

      刚刚换行

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

      有了这个

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

      【讨论】:

        猜你喜欢
        • 2015-07-05
        • 2014-08-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 2011-11-08
        • 2013-11-15
        相关资源
        最近更新 更多