Android:如何在代码中获取属性的值?

ab1*_*b11 77 android

我想在代码中检索textApperanceLarge的int值.我相信下面的代码是正确的方向,但无法弄清楚如何从TypedValue中提取int值.

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
Run Code Online (Sandbox Code Playgroud)

Mar*_*lts 118

您的代码只获取textAppearanceLarge属性指向的样式的资源ID ,即Reno指出的TextAppearance.Large.

要从样式中获取textSize属性值,只需添加以下代码:

int[] textSizeAttr = new int[] { android.R.attr.textSize };
int indexOfAttrTextSize = 0;
TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
Run Code Online (Sandbox Code Playgroud)

现在textSize将是textApperanceLarge指向的样式的文本大小(以像素为单位),如果未设置,则为-1.这假设typedValue.type的类型为TYPE_REFERENCE,所以你应该先检查一下.

数字16973890来自于它是TextAppearance.Large的资源ID

  • 奇迹般有效.为什么它必须如此复杂......六年之后,现在是不是没有那么模糊的方法呢? (4认同)

Ren*_*eno 49

运用

  TypedValue typedValue = new TypedValue(); 
  ((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
Run Code Online (Sandbox Code Playgroud)

对于字符串:

typedValue.string
typedValue.coerceToString()
Run Code Online (Sandbox Code Playgroud)

对于其他数据:

typedValue.resourceId
typedValue.data  // (int) based on the type
Run Code Online (Sandbox Code Playgroud)

在你的情况下它返回的是TYPE_REFERENCE.

我知道它应该指向TextAppearance.Large

这是:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?textColorPrimary</item>
</style>
Run Code Online (Sandbox Code Playgroud)

感谢马丁解决这个问题:

int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = context.obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0, -1);
Run Code Online (Sandbox Code Playgroud)


Ren*_*tik 12

Or in kotlin:

fun Context.dimensionFromAttribute(attribute: Int): Int {
    val attributes = obtainStyledAttributes(intArrayOf(attribute))
    val dimension = attributes.getDimensionPixelSize(0, 0)
    attributes.recycle()
    return dimension
}
Run Code Online (Sandbox Code Playgroud)


Rat*_*ata 5

这似乎是对@user3121370 的回答的调查。他们烧毁了。:O

如果你只需要获取一个维度,比如填充,minHeight(我的情况是:android.R.attr.listPreferredItemPaddingStart)。你可以做:

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemPaddingStart, typedValue, true);
Run Code Online (Sandbox Code Playgroud)

就像问题一样,然后:

final DisplayMetrics metrics = new android.util.DisplayMetrics();
WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
int myPaddingStart = typedValue.getDimension( metrics );
Run Code Online (Sandbox Code Playgroud)

就像删除的答案一样。这将允许您跳过处理设备像素大小,因为它使用默认设备指标。返回将是浮动的,您应该转换为 int。

注意您要获取的类型,例如 resourceId。