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?