1.什么是屏幕适配?
屏幕适配是将一款app适应于不同屏幕尺寸的设备上,比如说一般情况下手机和pad上的同一个app是不同的,这就是通过屏幕适配解决的。
其中屏幕适配有很多重要概念,屏幕尺寸、屏幕分辨率、屏幕像素密度。
屏幕尺寸:
屏幕尺寸指屏幕的对角线的长度,单位是英寸,1英寸=2.54厘米
比如常见的屏幕尺寸有2.4、2.8、3.5、3.7、4.2、5.0、5.5、6.0等。
屏幕分辨率:
屏幕分辨率是指在横纵向上的像素点数,单位是px,1px=1个像素点。一般以纵向像素*横向像素,如1960*1080。
屏幕像素密度:
屏幕像素密度是指每英寸上的像素点数,单位是dpi,即“dot per inch”的缩写。屏幕像素密度与屏幕尺寸和屏幕分辨率有关,在单一变化条件下,屏幕尺寸越小、分辨率越高,像素密度越大,反之越小。
dp、dip、dpi、sp、px:
px我们应该是比较熟悉的,前面的分辨率就是用的像素为单位,大多数情况下,比如UI设计、Android原生API都会以px作为统一的计量单位,像是获取屏幕宽高等。
dip和dp是一个意思,都是Density Independent Pixels的缩写,即密度无关像素,上面我们说过,dpi是屏幕像素密度,假如一英寸里面有160个像素,这个屏幕的像素密度就是160dpi,那么在这种情况下,dp和px如何换算呢?在Android中,规定以160dpi为基准,1dip=1px,如果密度是320dpi,则1dip=2px,以此类推。
而sp,即scale-independent pixels,与dp类似,但是可以根据文字大小首选项进行放缩,是设置字体大小的御用单位。
mdpi、hdpi、xdpi、xxdpi:
其实之前还有个ldpi,但是随着移动设备配置的不断升级,这个像素密度的设备已经很罕见了,所在现在适配时不需考虑。
mdpi、hdpi、xdpi、xxdpi用来修饰Android中的drawable文件夹及values文件夹,用来区分不同像素密度下的图片和dimen值。
2.怎样进行屏幕适配?
首先一个有4种屏幕适配,他们分别是尺寸单位适配、图片适配、文字适配以及布局适配。
1)布局适配
首先使用尺寸限定符(layout-large)通过创建一个文件
res/layout-large/main.xml
来完成上述设定:
让系统在屏幕尺寸>7英寸时采用适配平板的双面板布局
反之(默认情况下)采用适配手机的单面板布局
文件配置如下:
适配手机的单面板(默认)布局:res/layout/main.xml
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
如图
<适配尺寸>7寸平板的双面板布局::res/layout-large/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
如图
请注意:
两个布局名称均为main.xml,只有布局的目录名不同:第一个布局的目录名为:layout,第二个布局的目录名为:layout-large,包含了尺寸限定符(large)
被定义为大屏的设备(7寸以上的平板)会自动加载包含了large限定符目录的布局,而小屏设备会加载另一个默认的布局
2)尺寸单位适配
<resources>
<dimen name="btn_width" values="100dp"></dimen>
</resources>
<Button
android:layout_width="@dimenn_width"
android:layout_height="50dp"
android:text="hello"/>
3)图片适配
将相同图片放入xhdip、mdip中如下图
然后运行程序,这样不同分辨率的手机会出现不同的图片。
4)文字适配
首先创一个values-en的文件夹用于放英文
如下图
然后将中文下的代码改成英文代码如下
中文下
<resources>
<string name="app_name">屏幕适配</string>
<string name="btn_text">你好</string>
</resources>
英文下
<resources>
<string name="app_name">screen</string>
<string name="btn_text">hello</string>
</resources>