Android text size software too large

I have two szenarios:

Firstly:

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

Second in xml:

 android:textSize="@dimen/defaultTextSize" 

in /dimen.xml values โ€‹โ€‹I declared defaultTextSize with 20sp

In my first case, the text is much larger (and different in some scenarios) than in my second case. What for? I made a mistake?

+6
source share
4 answers

setTextSize() takes a block as a 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)) 
+11
source

Implementation of setTextSize(float size)

 public void setTextSize(float size) { setTextSize(TypedValue.COMPLEX_UNIT_SP, size); } 

In your case, what happens is that you scale the value specified in setTextSize , since getDimension returns the size times the metric. Try

 textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize)); 
+6
source

Have you tried using

  textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.defaultTextSize)); 
+1
source

TextView uses the Resources.getDimensionPixelSize method, not the Resource.getDimension for textSize.

0
source

Source: https://habr.com/ru/post/981352/


All Articles