首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 代碼中獲取主題屬性值:以 textAppearanceLarge 為例

     編輯:程式設計綜合問答

在 Android 開發中,常需動態獲取主題屬性(如 textAppearanceLarge)的具體數值(如字體大小)。直接用 TypedValue 只能拿到資源引用,需進一步通過 TypedArray 解析具體屬性。

正確獲取步驟

  1. 用 resolveAttribute 將屬性引用解析到 TypedValue。
  2. 根據 TypedValue.data(資源 ID)構建屬性數組,如 new int[]{android.R.attr.textSize}。
  3. 用 obtainStyledAttributes 獲取 TypedArray。
  4. 調用 getDimensionPixelSize 取得像素值。
  5. 最後 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 適配。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved