2015-04-07 91 views
2

我最近才必须在Android布局文件中设置xmlns属性。最初,当我添加第三方控件时,控件的XML中的某些属性没有用于标识名称空间的前缀。当我运行我的应用程序时,显示控件,但那些没有命名空间前缀的属性被忽略。只有在将xmlns添加到文件顶部并向属性添加前缀后,才能在运行时识别这些属性。以下是更正后的代码的样子:了解Android布局中的xmlns属性

xmlns:fab="http://schemas.android.com/apk/res-auto" 

    <com.getbase.floatingactionbutton.FloatingActionButton 
     android:id="@+id/ivFAB" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     fab:fab_icon="@drawable/ic_fab_star" 
     fab:fab_colorNormal="@color/pink_500" 
     fab:fab_colorPressed="@color/pink_100" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_marginRight="15dp" 
     android:layout_marginBottom="15dp" 
     android:visibility="visible" 
     /> 

她的xmlns前缀是'fab'。我不明白的是,没有名称空间和前缀,应用程序编译没有任何错误。为什么Android Studio不会抱怨它找不到fab_icon?为什么它只是忽略这些属性?我已经在不同的主题上看到了很多帖子,其中有人指出不用前缀,然后代码工作。所以我不知道发生了什么。在一些问题(像我的)有前缀是必需的,但在其他人不是?这是不同版本的Android Studio或SDK版本的问题吗?

回答

0

是的。即使您可以定义您自己的自定义布局属性。

第1步:创建一个视图的子类。

class PieChart extends View { 
    public PieChart(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 
} 

步骤2:定义自定义与res/values/attrs.xml<declare-styleable>属性。

<resources> 
    <declare-styleable name="PieChart"> 
     <attr name="showText" format="boolean" /> 
     <attr name="labelPosition" format="enum"> 
      <enum name="left" value="0"/> 
      <enum name="right" value="1"/> 
     </attr> 
    </declare-styleable> 
</resources> 

第3步:使用您的布局XML中的属性。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"> 
<com.example.customviews.charting.PieChart 
    custom:showText="true" 
    custom:labelPosition="left" /> 
</LinearLayout> 

步骤4:应用自定义属性您的观点。

public PieChart(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    TypedArray a = context.getTheme().obtainStyledAttributes(
     attrs, 
     R.styleable.PieChart, 
     0, 0); 

    try { 
     mShowText = a.getBoolean(R.styleable.PieChart_showText, false); 
     mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0); 
    } finally { 
     a.recycle(); 
    } 
} 

步骤5:添加属性和事件

属性是控制行为和观点外观的有力方式,但是当视图初始化,它们只能被读取。要提供动态行为,请为每个自定义属性公开属性getter和setter对。下面的代码片段展示了如何PieChart暴露了一个名为showText

public boolean isShowText() { 
    return mShowText; 
} 

public void setShowText(boolean showText) { 
    mShowText = showText; 
    invalidate(); 
    requestLayout(); 
} 

欲了解更多信息和细节特性,请阅读本link

+0

我的问题不是关于如何创建自定义属性。这是关于理解使用xmlns属性和前缀属性的需要或缺乏。 – AndroidDev

+1

如果您知道如何创建具有属性的自定义视图,那么很容易理解是否需要这些属性。现在考虑如果你有一个强制性的自定义属性,如果你不提供它会发生什么?你的观点会被初始化吗? –