自定義控制項7 自定義屬性二

2021-07-09 01:43:31 字數 2723 閱讀 7624

問題1 format =」reference|color」,比如自定義乙個按鈕,背景有可能是顏色也有可能是,該如何去獲取該屬性?

問題2 typedvalue是什麼鬼東西?

問題3 getfraction(index, base, pbase, defvalue);中的第2,3個引數是幹什麼的?

我的解決方法:

if (a.hasvalue(r.styleable

.customvolumcontrolbar_bg))

}

api—typedvalue | android 開發者

typedvalue

---android.util.typedvalue

container for

a dynamically typed data value. primarily used with resources for holding resource values.

翻譯過來就是:這個類是工具類,作為乙個動態容器,它存放一些資料值,這些值主要是resource中的值。

我們來理解一下:resource中到底有哪些值?layout、drawable、string、style、anim、dimens、menu、colors、ids這些值一些和螢幕適配有直接的關係。

有一些方法必然是可以讀取這些資源檔案資訊的,比如:

getdimension

(displaymetrics metrics)

再看具體的方法:

unit, float

value,displaymetrics metrics)

第乙個引數是單位,第二個引數是對應值,第三個***,封裝了顯示區域的各種屬性值。

public

static

float

value,

displaymetrics metrics)

return

0; }

其中單位為dip的,將其轉化為密度*值,也就是畫素值,而單位sp的也將其轉化為px值,因此該方法可以能進行

dip–>px

sp– >px

dp2sp(50) = 150

sp2dp(50) = 150

convertdiporpx(50) = 150

convertpxordip(50) = 17

將**執行實際結果與判斷結果一致。

轉化dp-px,px-dp,sp-px,px-sp

//轉換dip為px 

public

static

intconvertdiporpx(context context, int dip)

//轉換px為dip

public

static

intconvertpxordip(context context, int px)

//轉換sp為px

public

static

intsp2px(context context, float spvalue)

//轉換px為sp

public

static

intpx2sp(context context, float pxvalue)

getfraction(index, base, pbase, defvalue);
attrs.xml:

"fraction" type="fraction">5%

"parent_fraction" type="fraction">2%p

列印結果:

// 0.05f

getresources().getfraction(r.fraction

.fraction, 1, 1);

// 0.02f

getresources().getfraction(r.fraction

.parent_fraction, 1, 1);

// 0.10f

getresources().getfraction(r.fraction

.fraction, 2, 1);

// 0.10f

getresources().getfraction(r.fraction

.fraction, 2, 2);

// 0.04f

getresources().getfraction(r.fraction

.parent_fraction, 1, 2);

// 0.04f

getresources().getfraction(r.fraction

.parent_fraction, 2, 2);

具體的文件我就不翻譯了,簡單來說就是:

1 自定義百分數有兩種格式,5%和5%p

2 兩者的區別在於,如果5%,那麼在呼叫getfraction()時,會*base

如果是5%p,那麼會*pbase

引用:

android res.getfraction() - 學習記錄 - 部落格頻道 - csdn.net

android - how does one use resources.getfraction()? - stack overflow

自定義控制項及自定義屬性

自定義控制項在android開發中的重要性,是不言而喻,眾人皆知的。希望通過這二天的學習,能讓大家了解自定義控制項的原理,熟悉自定義控制項的使用步驟,並能寫出一些普通的效果。內容介紹 1 使用系統控制項,實現自定義的效果,案例有 優酷環形選單 廣告條 viewpager 下拉列表 spinner 2...

Android自定義控制項 自定義屬性

自定義屬性的過程 1.在res values資料夾中建立attrs的xml檔案。2.寫入標籤,定義子標籤attr,放入自定義屬性的名稱。format 可以用 來同時使用 1 reference 參考某一資源id 2 color 顏色值 3 boolean 布林值 4 dimension 尺寸值 帶有...

android自定義控制項新增自定義屬性

1 如果是自定義控制項,請在style.xml中或attrs.xml中宣告屬性 attr declare styleable 2 在theme中使用自定義的屬性,可以再多個主題中定義不同的屬性值 customize your theme here.color colorprimaryitem col...