Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android text-size programmatically too big

I have two szenarios:

First:

 textView.setTextSize(getResources().getDimension(R.dimen.defaultTextSize));

Second in xml:

android:textSize="@dimen/defaultTextSize"

in values/dimen.xml i have declared defaultTextSize with 20sp

In my first case the text is much bigger (and different in some screenresulutions) than in my second case. Why? Have I done a mistake?

like image 716
Ef Ge Avatar asked Jan 21 '15 16:01

Ef Ge


People also ask

How do I change font size in android programmatically?

To set Android Button font/text size, we can set android:textSize attribute for Button in layout XML file. To programmatically set or change Android Button font/text size, we can pass specified size to the method Button. setTextSize(specific_size).

How do I change font size in XML?

Adding fonts to a TextView To set a font for the TextView , do one of the following: In the layout XML file, set the fontFamily attribute to the font file you want to access. Open the Properties window to set the font for the TextView .


1 Answers

setTextSize() takes unit as pixel

Use this

public float pixelsToSp(float px) 
{
    float scaledDensity = _context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

textView.setTextSize(pixelsToSp(getResources().getDimension(R.dimen.defaultTextSize)));

or

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize))
like image 112
Rohit5k2 Avatar answered Nov 03 '22 00:11

Rohit5k2