国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Andorid自定義attr的各種坑

2019-12-12 06:34:10
字體:
來源:轉載
供稿:網友

在開發Andorid應用程序中,經常會自定義View來實現各種各樣炫酷的效果,在實現這吊炸天效果的同時,我們往往會定義很多attr屬性,這樣就可以在XML中配置我們想要的屬性值,以下就是定義屬性值可能遇到的各種坑。

大家都知道怎么定義attr屬性,一般如下:

<declare-styleable name="Sample">  <attr name="custom" format="string|reference" /></declare-styleable>

先聲明一個styleable名稱,name名稱最好見名知義,一個styleable里面可以有多個attr屬性,每一個attr都含有一個name,同時需要指明所能賦值的類型,這是是依靠format來定義的。定義好之后就可以在自定義View中使用,來實現各種吊炸天的效果,使用如下:
xml中使用:

<com.sample.ui.widget.Custom  android:id="@+id/custom_view"  android:layout_width="130dp"  android:layout_height="130dp"  android:layout_gravity="center_horizontal"  android:layout_marginTop="90dp"  app:text="@string/custom_desc"  />

記得聲明 xmlns:app=”http://schemas.android.com/apk/res-auto”, app 可以隨便取名
代碼中獲取值:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Sample);String value = a.getString(R.styleable.Sample.custom);a.recycle();

根據format不同,還有getDimension,getColor等方式獲取值。

上面只是描述了一般定義的方式,但他不是今天的主題,今天的主題是可能遇到的各種坑:

1:項目中只包含一個attr.xml,出現 Attribute “custom” has already been defined,參考鏈接

<declare-styleable name="Sample">    <attr name="custom" format="string|reference" /></declare-styleable><declare-styleable name="Sample1">    <attr name="custom" format="string|reference" /></declare-styleable>

如上聲明了兩個styleable,同時包含了相同的屬性custom,這時在編譯時會提示Attribute “xxx” has already been defined,表示相同屬性重復定義,相同styleable name不能再同一個attr.xml中重復定義,styleable name不一致attir也不能重復定義,attr format屬性不影響重復定義結果。因此可以采用如下方法解決該問題:

a:重命名相同屬性名,將其中一個改為不同的名字
b:提取重復定義attr,作為公共屬性,方式如下:

<attr name="custom" format="string|reference" /><declare-styleable name="Sample">  <attr name="custom" /></declare-styleable><declare-styleable name="Sample1">  <attr name="custom" /></declare-styleable>

2: 項目中引用了多個外部項目,出現 Attribute “custom” has already been defined
不同的導入項目中,可能包含多個attr.xml,這樣在定義時極有可能重復定義,他又分為如下兩種情況:

a: 主項目,引用庫包含同名styleable name,如:
主項目:

<declare-styleable name="Sample">  <attr name="custom" /></declare-styleable>

引用庫:

<declare-styleable name="Sample">  <attr name="custom" /></declare-styleable>

這種情況下,編譯是不會出現錯誤的,可以正常編譯。

b: 主項目,引用庫包含不同名styleable,但是有同名attr,如;
主項目:

<declare-styleable name="Sample">  <attr name="custom" /></declare-styleable>

引用庫:

<declare-styleable name="Sample1">  <attr name="custom" /></declare-styleable>

編譯時會出現 Attribute “custom” has already been defined。由此可以得出,在項目中引用各種庫,模塊時,各個不同的模塊定義attr,要遵循以下規則,
1:全部不能重復定義,全部不能重復很難實現,不同的團隊,不同的產品是極有可能重復定義,因此該方式很難實現。
2:各個不同模塊,定義時加上模塊前綴,這種方式重復幾率就小很多,編譯時再將重復的重命名就ok了。

以上就是本文的全部內容,希望對大家的學習有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿克苏市| 鄱阳县| 卫辉市| 巴林右旗| 庆安县| 原平市| 增城市| 乌海市| 信丰县| 车致| 伊川县| 遂溪县| 陆河县| 右玉县| 平罗县| 潢川县| 东乡| 靖西县| 潜山县| 镇远县| 松原市| 建始县| 彝良县| 藁城市| 沽源县| 无极县| 阜南县| 绵竹市| 温州市| 通州区| 兴安县| 新河县| 岗巴县| 万盛区| 长丰县| 华亭县| 礼泉县| 孝感市| 潼南县| 克东县| 沈阳市|