Reputation: 6246
I'm trying to set the text size of a TextView.
I'm using this code what I've seen around in a few places
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView title = new TextView(getContext());
title.setLayoutParams(lp);
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, getContext().getResources().getDimension(R.dimen.small_font));
title.setText("Cannot find our servers");
addView(title);
small_font is 12sp.
When I run the app, this is what it looks like (Cannot find our servers)
That certainly doesn't look like 12sp to me. How do I get it so the text is the right size?
Upvotes: 0
Views: 204
Reputation: 3497
You are using scaled pixels(COMPLEX_UNIT_SP
). It means that text will have equal size on different scrrens with different sizes. Try to use COMPLEX_UNIT_DP
instead.
Upvotes: 1
Reputation: 38409
try below code:-
TextView text = new TextView(this);
text.setText("text");
text.setTextSize(12 * getResources().getDisplayMetrics().density);
or
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DP, 12);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 12);
or
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
Upvotes: 1