【问题标题】:Custom Layout, losing custom defined attributes in attrs.xml自定义布局,丢失 attrs.xml 中的自定义属性
【发布时间】:2013-11-20 18:59:12
【问题描述】:

我在 attrs.xml 中有以下内容

  <declare-styleable name="ToolsView">
        <attr name="width_behaviour" format="reference" />
    </declare-styleable>

我的布局文件中有以下代码:

  <com.hidden.hidden2.view.ToolsView
        xmlns:app="http://schemas.android.com/com.hidden.hidden2"
        android:id="@+id/page_toolbar_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:background="@drawable/tools_background"
        android:gravity="center_horizontal"
        android:layerType="software"
        android:visibility="visible"
        app:width_behaviour="@integer/tools_view_width_behaviour" />

但是,当我尝试在类的构造函数中读取 app:width_behaviour 时

if (attributeSet != null) {
            TypedArray a = getContext().obtainStyledAttributes(attributeSet, R.styleable.ToolsView, 0, 0);
            final int N = a.getIndexCount();
            for (int i = 0; i < N; i++) {
                int attr = a.getIndex(i);
                switch (attr) {
                case R.styleable.ToolsView_width_behaviour:
                    widthBehaviour = a.getInteger(attr, -1);
                    break;
                }
            }

            a.recycle();

属性集不为null,但N为0——没有获取到自定义属性!所以它永远不会进入 for 循环。

知道为什么吗?我已经习惯了很多布局,这是我第一次遇到问题。

【问题讨论】:

    标签: android xml layout view merge


    【解决方案1】:

    将属性的格式更改为整数或维度(取决于您在 width_behaviour 下的意思),它应该可以工作。参考是为了另一个目的。

    【讨论】:

    • 还是不行? hhh...什么是getContext?为什么不使用 construstor 参数中的上下文?
    • 超级构造函数已经执行,所以技术上我可以从视图的 getContext() 中获取它。我没有直接得到它,因为这是在 super(context, attrs) 调用之后定义的初始化方法中。无论如何,我发现了错误,请参阅下面的答案。
    • 是的,我看到你修好了)
    【解决方案2】:

    哎哟。这是一个相当愚蠢的错误。

    查看 xmlns:app 的定义 - xmlns:app="http://schemas.android.com/com.hidden.hidden2" 应该是 xmlns:app="http://schemas.android.com/apk/res/com.hidden.hidden2"

    我的声明中不知何故缺少 /apk/res/ 部分。

    希望有一天这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 2012-07-01
      相关资源
      最近更新 更多