4

I have one textview and it has size as 32sp in xml.

android:textSize="32sp"

I wanted to change it as 28sp programmatically. So i used the below code.

txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.twenty_eight_sp));

But the above code is adding the 28sp to 32sp. So the font became too large. I don't want to add the font size, I want to set a new font size.

Can anyone suggest me.

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
simple
  • 159
  • 1
  • 9
  • use TypedValue.COMPLEX_UNIT_PX instead of TypedValue.COMPLEX_UNIT_SP refer this https://stackoverflow.com/questions/14540293/get-dimension-from-xml-and-set-text-size-in-runtime?answertab=active#tab-top – nik Nov 16 '18 at 05:50

4 Answers4

8

You have to change it to TypedValue.COMPLEX_UNIT_PX because getDimension(id) returns a dimen value from resources and implicitly converted to px.

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
           getResources().getDimension(R.dimen.result_font));
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Rashpal Singh
  • 633
  • 3
  • 13
1
txt.setTextSize(TypedValue.COMPLEX_UNIT_SP,getResources().getDimension(R.dimen.twenty_eight_sp));
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Sari Masri
  • 206
  • 1
  • 10
1

check this link https://developer.android.com/reference/android/widget/TextView#setTextSize(int,%20float)

consider both functions as per your requirement

enter image description here

Harsh
  • 363
  • 4
  • 14
1

Try this

txt_home.setTextSize(12);
Android Geek
  • 8,956
  • 2
  • 21
  • 35