问题
I have a home screen widget with TextView:
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:singleLine="true"
android:textStyle="bold" />
I need to get the size of this text. I am trying to get default TextView's size text like this:
TextView defaultTextView = new TextView(context);
float sourceTextSize = defaultTextView.getTextSize();
And sourceTextSize contains 21. But that is wrong value, because if I set this using remoteViews.setFloat(R.id.textView, "setTextSize", 21), it makes my text bigger.
How to get default text size of TextView on widget?
回答1:
Actually defaultTextView.getTextSize() returns size in pixels and setTextSize(size) takes input as sp, So your text becomes bigger. Thus instead of directly setting up the text size, first convert them according to density.
float sourceTextSize = defaultTextView.getTextSize();
TextView.setTextSize(sourceTextSize / getResources().getDisplayMetrics().density);
Here, getResources().getDisplayMetrics().density will returns the screen density as-
0.75 - ldpi
1.0 - mdpi
1.5 - hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi
Screen Density
回答2:
You are right from your point of you. When you getting from default text view then it will return sp value. because default textsize format is sp. And while you setting it with 21 then it will set with pixel. so size varies with screen size.
Try to experiment with different size devices.
Hope you understand.
来源:https://stackoverflow.com/questions/28411099/how-to-get-default-text-size-from-textview-on-widget