我需要在sp
单位中获取TextView
的当前TextSize
。
但getTextSize()
返回以像素
为单位的大小。所以是否有一种方法可以将像素转换为sp
?
使用这个
public static float pixelsToSp(Context context, float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}
如果你想测试这个方法是否正常工作,请使用以下代码片段
XML
<TextView
android:id="@+id/txtHelloWorld"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/txtHelloWorld2"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Java
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView helloWorldTextView = (TextView) rootView.findViewById(R.id.txtHelloWorld);
TextView helloWorldTextView2 = (TextView) rootView.findViewById(R.id.txtHelloWorld2);
helloWorldTextView2.setTextSize(pixelsToSp(getActivity(), helloWorldTextView.getTextSize()));
两个 TextView 的字体大小应该相同。
请查看DisplayMetrics类,其中包含densityDpi
和scaledDensity
两个字段。
使用示例:
float sp = px / getResources().getDisplayMetrics().scaledDensity;
DisplayMetrics
类具有字段densityDpi
和scaledDensity
,而不是方法。对于缩放,应使用density
字段而不是densityDpi
。 - Ted Hopp看到在运行时调整的公共字段有点奇怪,但它确实有效。标准 DPI 是 160,所以无论您的设备 DPI 是多少,比如 240,密度和缩放密度都将显示 240/160=1.5。以下是像素和 sp 之间的转换方式:px=1.5*sp。
DP -> PX
,PX -> DP
,SP to PX
和PX to SP
的转换。 - Suragch