在Android中获取默认文本大小(以像素为单位)

4
我需要知道当前默认的Android字体大小(以像素为单位)。我复制了一个非常类似的问题这里列出的方法。但是,我得到的总是-1而不是以像素为单位的大小。有任何想法我做错了什么吗?
这是代码:
    Context context = getActivity();
    TypedValue typedValue = new TypedValue(); 
    context.getTheme().resolveAttribute(android.R.attr.textAppearance, typedValue, true);
    int[] textSizeAttr = new int[] { android.R.attr.textSize };
    TypedArray a = context.obtainStyledAttributes((AttributeSet) typedValue.string, textSizeAttr);
    textSize = a.getDimensionPixelSize(0, -1);
    Log.e("Metrics", "text size in dp = " +  String.valueOf(textSize));
    a.recycle()
2个回答

6

获取textView的文本大小非常简单,以下是代码:

textView.getTextSize();

返回此TextView中默认文本大小的大小(以像素为单位)


1
证明:http://developer.android.com/reference/android/widget/TextView.html#getTextSize%28%29 - Pragnani
有趣的是,您的回答和下面的回答给出了不同的文本大小...这个是28像素,下面的方法是32像素。我需要调查哪个答案是正确的。 - lynvie
我将textView布局的边界指定为28像素(您的方法)或32像素(下面的方法)。 28像素截断了文本底部,而32像素则刚好合适。 但仔细检查后,我发现顶部有填充,而32像素似乎考虑到了填充,而28像素只是文本。 因此,我接受了您的答案! - lynvie

1

只需更改此代码行

TypedArray a = context.obtainStyledAttributes((AttributeSet) typedValue.string, textSizeAttr);

 TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);

这个修正了我的错误。然而,正如我在上面的评论中指出的那样,这两种解决方案都给出了两个答案(28像素对比32像素)。看起来这个方法返回的是文本大小加上填充,而textView.getTextSize()只给出了文本大小的像素值。真希望我能接受两个回答!谢谢。 - lynvie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接