簡體   English   中英

了解Android布局中的xmlns屬性

[英]Understanding the xmlns attribute in an Android layout

我只是最近才不得不在Android布局文件中設置xmlns屬性。 最初,當我添加第三方控件時,控件的XML中的某些屬性沒有前綴來標識名稱空間。 當我運行我的應用程序時,將顯示該控件,但是那些沒有名稱空間前綴的屬性將被忽略。 只有在將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? 為什么只忽略這些屬性? 我在整個stackoverflow上看到了很多關於不同主題的文章,其中有人指出省略前綴,然后代碼起作用。 所以我不知所措。 在某些問題(例如我的問題)中,需要前綴,但在其他問題中則不是嗎? 這是Android Studio的不同版本還是SDK的版本有問題?

是。 即使您可以定義自己的自定義布局屬性。

步驟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:添加屬性和事件

屬性是控制視圖行為和外觀的一種有效方法,但是只有在初始化視圖時才能讀取它們。 要提供動態行為,請為每個自定義屬性公開一個屬性獲取器和設置器對。 下面的代碼片段展示了如何PieChart公開了一個名為財產showText

public boolean isShowText() {
   return mShowText;
}

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

有關更多信息和詳細信息,請閱讀此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM