sea*_*kej 141
用这个
public static float pixelsToSp(Context context, float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}
Run Code Online (Sandbox Code Playgroud)
如果您想测试此方法是否正常,请使用此代码段
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"
/>
Run Code Online (Sandbox Code Playgroud)
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()));
Run Code Online (Sandbox Code Playgroud)
两个TextView的字体大小应该相同.
Gab*_*gut 35
请参阅DisplayMetrics类,它包含densityDpi和的字段scaledDensity.
用法示例:
float sp = px / getResources().getDisplayMetrics().scaledDensity;
Run Code Online (Sandbox Code Playgroud)
很奇怪看到在运行时调整的公共字段,但它的工作原理.标准Dpi是160,所以无论你的设备Dpi是什么,比如240,密度和scaledDensity都会显示240/160 = 1.5这就是你在像素和sp之间转换的方式:px = 1.5*sp
| 归档时间: |
|
| 查看次数: |
60474 次 |
| 最近记录: |