Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android xmlns 命名空間是什麼?基本概念與自定義屬性實作

編輯:關於 Android 程式設計

Android xmlns 的作用與自定義實例

xmlns:android="https://schemas.android.com/apk/res/android" 的作用如下:

它是 XML 的命名空間宣告。有了它,編輯器才能透過 Alt+/ 提供提示,告訴你可以填什麼、不該填什麼、什麼寫法正確、什麼錯誤,可以理解為一份語法定義檔。

更實際的作用是:執行時系統靠它來識別各控件的屬性。若這行寫錯,編譯階段往往不會報錯,但一執行就會出問題,例如提示未指定寬度等。這個宣告不需要連網。

那麼 Android 自定義的 xmlns 怎麼寫?語法規則是:

在使用到自定義 View 的 XML 布局檔根節點上加入 xmlns:前綴="https://schemas.android.com/apk/res/你的應用程式包路徑"。

以下是一個簡單範例:

結構圖:

MyView.java

 package kexc.myView; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.TextView; public class MyView extends TextView { private String mString = "Welcome to Kesion's blog"; public MyView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF); float textSize = a.getDimension(R.styleable.MyView_textSize, 36); mString = a.getString(R.styleable.MyView_title); setText(mString); setTextSize(textSize); setTextColor(textColor); } } 

 main.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:test="https://schemas.android.com/apk/res/kexc.myView" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <kexc.myView.MyView android:layout_width="fill_parent" android:layout_height="fill_parent" test:title="wo shi text" test:textSize="20px" test:textColor="#fff" /> </LinearLayout> 

 屬性檔 value/attrs.xml

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="textColor" format="color"/> <attr name="textSize" format="dimension" /> <attr name="title" format="string"/> </declare-styleable> </resources> 

執行結果:

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved