本文将继续记录学习Android studio中的简单控件的设置文本大小
设置文本大小同样有两种方式分别为:
(1)在Java代码中调用setTextSize方法,即可指定文本大小
(2)在xml文件中则是通过属性android:textSize指定文本大小,此时需要指定字号单位。而字号单位分为以下三种:
px:是手机屏幕的最小显示单位,只与设备显示屏有关
dp:是与设备无关的显示单位,只与屏幕的尺寸有关
sp:专门用来设置字体大小,可在系统设置中调整字体大小
下面为在Java代码中实现字体大小控制的具体代码:
package com.example.chapter03;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class TextSizeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_size);
TextView tv_hello = findViewById(R.id.tv_hello);
tv_hello.setTextSize(30);
}
}
Java的实现非常简单,因此我们将着重讲解在xml中的控制字体大小的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30px"/>
</LinearLayout>
使用xml实现时为了更明显的显示出来,我们使用orientation将布局格式转化为垂直格式,然后使用textSize设置字体大小,但是如果我们不加“px”,程序会报错提示你要加一个单位,那么接下来为大家补充一下在Android中的一些关于字体大小的知识点
px:称为像素,也叫图像元素,是图像构成的基本单位,单个像素的大小并不固定,跟随屏幕大小和像素数量的关系变化
Resolution:分辨率,是指屏幕的垂直和水平方向的像素数量,如果分辨率为1920*1080,那就是垂直方向有19920个像素水平方向上有1080个像素
Dpi:像素密度,是指屏幕上每英寸(一英寸=2.54厘米)距离中有多少像素点
Density:密度,是指屏幕上每平方英寸中含有的像素点数量
Dip/dp:设备独立像素,同一个单位在不同设备上有不同的显示效果,具体效果与设备的密度有关
那么我们在实际开发中如何计算dp,公式来了!
我们以一个4。95英寸1920*1080的手机为例:
Dpi:
1.计算直角边像素数量:1920^2+1080^2=2202^2(勾股定理)
2.计算DpI:2202/4.95=445
3.得到这个设备的DPI为445(每英寸的距离中有445个像素)
Density:
上面得到每英寸中有440像素,那么density为每平方英寸中的像素数量,应该为:445^2=198025
Dip
所有显示到屏幕上的图像都是以px为单位,Dip是我们开发中使用的单位长度,最后需要转化为px,计算这个设备上1dip等于多少px:
px=dip/dpi/160
根据换算关系320*480分辨率,3.6英寸的手机:dpi为160,1dp为1px
总结:
(1)对于相同分辨率的手机,屏幕越大,同DP的组件占用屏幕比例越小
(2)对于相同尺寸的手机,即使分辨率不同,同DP的组件占用屏幕比例相同
综上所述:
dp的UI效果只在相同尺寸的屏幕上相同,如果屏幕尺寸过大,则需要重做dp适配
这也是平板需要单独做适配的原因,可见dp不是比例
接下来,将以代码的形式为大家展示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30px"/>
<TextView
android:id="@+id/tv_dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dp" />
<TextView
android:id="@+id/tv_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30sp" />
</LinearLayout>
运行结果如下,从上向下分别对于px,dp,sp
当我们在虚拟机中改变字体大小会发生什么呢?
大家很明显能够看到sp单位的字体大小发生了改变
以上便是设置文本大小的知识点。