2013-11-20 108 views
0

失去自定义的属性,我已经中attrs.xml以下自定义布局,在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" /> 

然而,当我尝试阅读应用:在我的课

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(); 

的属性进行设置的构造width_behaviour不为空,但N为0 - 没有自定义attri butes获得!所以它永远不会进入for循环。

任何想法为什么是这样?我习惯了很多布局,这是我第一次遇到问题。

回答

1

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

+0

你在这里是正确的,但这并不是问题。 – George

+0

它仍然不是武器?呃...什么是getContext?你为什么不使用construstor param的上下文? – Leonidos

+0

超级构造函数已经执行,所以技术上我可以从视图的getContext()中取出它。我没有直接获取它,因为这是在super(context,attrs)调用后定义的初始化方法中。无论如何,我发现错误,请参阅下面的答案。 – George

0

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

请参阅xmlns的定义:app - xmlns:app =“http://schemas.android.com/com.hidden.hidden2” 它应该是xmlns:app =“http://schemas.android。 com/apk/res/com.hidden.hidden2“

/apk/res/part在我的声明中不知所踪。

希望这可以帮助别人有一天。