我想按原样加载值。
我有两个dimension.xml文件,一个在/res/values/dimension.xml中,另一个在/res/values-sw360dp/dimension.xml中。
从源代码我想做的事情
getResources().getDimension(R.dimen.tutorial_cross_marginTop);
这是可行的,但我得到的值乘以屏幕密度因子(1.5为hdpi, 2.0为xhdpi,等等)。
我也试着去做
getResources().getString(R.dimen.tutorial_cross_marginTop);
这将在原则上工作,但我得到了一个以“dip”结尾的字符串…
如果你只是想动态改变字体大小,那么你可以:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.tutorial_cross_marginTop))
正如@achie的回答,你可以像这样从dimensions .xml中获取dp:
val dpValue = (resources.getDimension(R.dimen.tutorial_cross_marginTop)/ resources.displayMetrics.density).toInt()
或者得到这样的sp
val spValue = (resources.getDimension(R.dimen.font_size)/ resources.displayMetrics.scaledDensity).toInt()
关于Resources.java #{getDimension}
/**
* Retrieve a dimensional for a particular resource ID. Unit
* conversions are based on the current {@link DisplayMetrics} associated
* with the resources.
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
*
* @return Resource dimension value multiplied by the appropriate
* metric.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @see #getDimensionPixelOffset
* @see #getDimensionPixelSize
*/
资源维度值乘以相应的值