为什么来自attrs的XML自定义布局属性在LayoutParams中没有影响?

时间:2016-04-02 18:55:35

标签: android xml

我正在尝试使用CustomLayout,并且正在关注Android页面中的步骤。当我尝试按照步骤操作时,我遇到了 my_layout_position 的问题。

假设我有 res / values / attrs.xml 文件,其中包含

 <resources>   
    <declare-styleable name="mycostume_layout">

        <attr name="my_layout_position" format="enum">
            <enum name="middle" value="0" />
            <enum name="left" value="1" />
            <enum name="right" value="2" />
            <enum name="bottom" value="3"/>
        </attr>
    </declare-styleable>
</resources>

然后我有 res / layout / myapp_main.xml 并在Button中设置app:my_layout_position =“right”

<com.example.App.MyLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res">
    <Button
       android:id="@+id/button1"
       android:layout_width="145dp"
       android:layout_height="wrap_content"
       app:my_layout_position="right"
       android:text="@string/Next"
    />

</com.example.App.MyLayout>

然后在文件 App / src / com / example / app / MyLayout.java

public static class LayoutParams extends ViewGroup.MarginLayoutParams {

     public int gravity = Gravity.TOP | Gravity.START;

     public static final int POSITION_MIDDLE = 0;
     public static final int POSITION_LEFT = 1;
     public static final int POSITION_RIGHT = 2;
     public static final int POSITION_BOTTOM = 3;

     public int position = POSITION_MIDDLE;


     public LayoutParams(Context c, AttributeSet attrs) {
        super(c, attrs);

     TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.mycostume_layout);            
     position = a.getInt(R.styleable.mycostume_layout_my_layout_position,position);

     System.out.println("position = " + position);

     a.recycle();
}

位置返回0.我希望自myapp_main.xml中放置app:my_layout_position =“right”以来该位置为2。

1 个答案:

答案 0 :(得分:0)

所以问题出现在文件 res / layout / myapp_main.xml 中,我必须指定服装布局的来源。在我的情况下,它在我的应用程序中,所以我必须指定 com.example.App 或什么是您的包名称

 (correct)   xmlns:app="http://schemas.android.com/apk/res/com.example.App"
 (wrong)     xmlns:app="http://schemas.android.com/apk/res"

现在我们可以使用app:my_layout_position。

我想知道为什么XML首先没有显示错误,它可能是eclipse(不确定)。不过要知道它会很有趣:)

<com.example.App.MyLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.example.App">
    <Button
       android:id="@+id/button1"
       android:layout_width="145dp"
       android:layout_height="wrap_content"
       app:my_layout_position="right"
       android:text="@string/Next"
    />

</com.example.App.MyLayout>
相关问题