4

I need to know the size in pixels of the current default Android font. I copied the approach listed in a very similar question here. However, instead of getting the size in pixels, I always get -1. Any ideas what I'm doing wrong?

Here's the code:

    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()
Community
  • 1
  • 1
lynvie
  • 1,028
  • 1
  • 14
  • 25

2 Answers2

6

It's quite simple to get text size of a textView here is the code

textView.getTextSize();

Returns the size (in pixels) of the default text size in this TextView

Mudassar Shaheen
  • 1,397
  • 1
  • 9
  • 15
  • 1
    Proof http://developer.android.com/reference/android/widget/TextView.html#getTextSize%28%29 – Pragnani Feb 27 '13 at 06:01
  • Interestingly enough, both your answer and the one below give me different text sizes... 28pixels for this one and 32 for the method below. I need to investigate which answer is right. – lynvie Feb 27 '13 at 06:58
  • I specified the boundaries of the textView layout as either 28 pixels (your method) or 32 pixels (the method below). The 28 pixels cut off the bottom of the text whereas the 32 pixels was just right. But upon closer inspection, I see there's padding at the top and the 32 pixels seems to account for the padding whereas the 28 pixels was just the text. So I accepted your answer! – lynvie Feb 27 '13 at 07:33
1

Just change this line of code

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

To

 TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
Ahmad Kayyali
  • 8,233
  • 13
  • 49
  • 83
  • This corrected my mistake. However, as I noted in a comment above, the two solutions each gave two answers (28 pixels vs. 32 pixels). It looks like this method returns text size + padding whereas the textView.getTextSize() just gave me the text size pixels. I wish I could accept both responses! Thanks. – lynvie Feb 27 '13 at 07:35