问题
I have variable at dimens.xml
<resources>
<dimen name="btn_text_size">12sp</dimen>
</resources>
And i can use it in layout file:
<TextView
android:textSize="@dimen/btn_text_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dialog_tags_complete"
/>
or programmatically
tagButton.setTextSize(c.getResources().getDimension(R.dimen.tag_text_size));
But this 2 methods give different results. I know that getDimension
are based on the current DisplayMetrics associated with the resources.
But what should i do to make this 2 ways looks the same?
回答1:
setTextSize( float )
expects a scaled pixel value. So, setTextSize( 12 )
would give you the desired result. However, getDimension()
and getDimensionPixelSize()
return the size in units of pixels, so you need to use the unit-typed variant of setTextSize()
as follows:
setTextSize( TypedValue.COMPLEX_UNIT_PX, getDimensionPixelSize( R.dimen.tag_text_size ) );
回答2:
tagButton.setTextSize(c.getResources().getDimensionPixelSize(R.dimen.tag_text_size));
this will work just fine :) You should also remember that textView has a setTextSize(int unit,float size), which should be used while setting size from code but not from xml dimen.
回答3:
I have currently the same thing. Did set a dimension in dimens.xml and applied it programmatically, which is 3 times that big, than when settings via xml.
I checked also:
TextView.getTextSize() = 92f
getResources().getDimension(R.dimen ...) = 92f
TextView.setTextSize(92) != TextView with size from XML, other flags like TypedValue.COMPLEX_UNIT_PX make it even bigger.
The default setTextSize does apply COMPLEX_UNIT_SP by default btw. So once again, the Android API is inconsistent, so setting programmatically only and adapt sizes, so they fit, will be my solution.
Edit: Setting text size programmatically under Galaxy Note 2 (4.4.2) vs Note 4 (5.0.1) leads to a totally different result -.-
来源:https://stackoverflow.com/questions/19496888/set-text-size-in-xml-or-programmatically