天天看點

Android 筆記 讀取style檔案的屬性

讀取style檔案屬性

有時候需要用代碼的方法讀取style檔案的屬性,用來動态設定狀态

int[] attrs = new int[]{R.attr.(屬性名)};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(, );
view.setBackgroundResource(backgroundResource);
typedArray.recycle();
           

obtainStyledAttributes()

用來讀取屬性資訊,這個方法還有其他的重載方法,這個隻有一個參數的就是從目前style檔案讀取資訊。

TypedArray

用于記錄資訊,在使用完以後記得調用

typedArray.recycle()

TypedArray

How do I add selectableItemBackground to an ImageButton programatically? (from stack overflow)