2

I get different text sizes when I set text size of a TextView by layout XML and Java code. My layout looks like the following.

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Some text"
    android:textSize="18sp"/>

And I tried setting text size in Java by following two ways.

Option 1

TextView titleView = (TextView) view.findViewById(R.id.title);
titleView.setTextSize(18 * getResources().getDisplayMetrics().density);

Option 2

TextView titleView = (TextView) view.findViewById(R.id.title);
titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

The text size set by Java code (both option 1 and 2) appears much bigger than the text size set by layout XML. What am I doing wrong?

tilmik
  • 143
  • 1
  • 2
  • 11
  • See this http://stackoverflow.com/questions/6784353/inconsistency-when-setting-textview-font-size-in-code-and-in-resources – KishuDroid Oct 28 '15 at 11:07
  • Please do not discourage people from asking questions by down-voting it within 5 mins of submit. I took some time searching it and some more time writing that question. There is always chance that I don't find the exact post on stackoverflow that I am looking for. – tilmik Nov 24 '15 at 04:46

1 Answers1

3

You will need to reduce the size by screen density

titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, (18 / getResources().getDisplayMetrics().density));
sajadkk
  • 764
  • 1
  • 5
  • 19
  • Thanks. Also found out that using `TypedValue.COMPLEX_UNIT_PX` instead of `TypedValue.COMPLEX_UNIT_SP` gives correct text size. – tilmik Oct 28 '15 at 18:08