【问题标题】:Getting default text size in pixels in Android在Android中获取默认文本大小(以像素为单位)
【发布时间】:2013-02-27 04:46:26
【问题描述】:

我需要知道当前默认 Android 字体的像素大小。我复制了一个非常相似的问题here 中列出的方法。但是,我总是得到-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()

【问题讨论】:

    标签: android layout fonts


    【解决方案1】:

    获取 textView 的文本大小非常简单 这是代码

    textView.getTextSize();
    

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

    【讨论】:

    • 有趣的是,你的答案和下面的答案都给了我不同的文本大小......这个是 28 像素,下面的方法是 32。我需要调查哪个答案是正确的。
    • 我将 textView 布局的边界指定为 28 像素(您的方法)或 32 像素(以下方法)。 28 像素切断了文本的底部,而 32 像素恰到好处。但经过仔细检查,我发现顶部有填充,32 像素似乎是填充的原因,而 28 像素只是文本。所以我接受了你的回答!
    【解决方案2】:

    改这行代码就行了

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

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

    【讨论】:

    • 这纠正了我的错误。但是,正如我在上面的评论中指出的那样,这两种解决方案都给出了两个答案(28 像素对 32 像素)。看起来这个方法返回文本大小 + 填充,而 textView.getTextSize() 只是给了我文本大小像素。我希望我能接受这两种回答!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多