在 Android 開發中,常需動態獲取主題屬性(如 textAppearanceLarge)的具體數值(如字體大小)。直接用 TypedValue 只能拿到資源引用,需進一步通過 TypedArray 解析具體屬性。
resolveAttribute 將屬性引用解析到 TypedValue。TypedValue.data(資源 ID)構建屬性數組,如 new int[]{android.R.attr.textSize}。obtainStyledAttributes 獲取 TypedArray。getDimensionPixelSize 取得像素值。recycle() 釋放資源。TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
int[] textSizeAttr = new int[] { android.R.attr.textSize };
TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(0, -1); // 索引 0 對應 textSize
a.recycle();
// textSize 即為 textAppearanceLarge 對應的字體大小(px)
typedValue.data 在引用類型時存儲資源 ID,而非直接值。getDimensionPixelSize 返回默認值(示例中 -1)。textColor、fontFamily 等屬性,只需換屬性數組。掌握這套流程,即可靈活讀取任何主題屬性的具體數值,實現動態 UI 適配。