android-屏幕适配

发表于:,更新于:,By Sally
大纲
  1. 1. 基本概念
  2. 2. 尽可能的使用相对布局,match_parent,wrap_content,weigth等属性
  3. 3. 使用限定符
    1. 3.1. 屏幕方向限定符
    2. 3.2. 为个分辨率的尺寸,建立一个文件标准
  4. 4. .9 图片
  5. 5. 图片准备

基本概念

  • 屏幕尺寸:屏幕对角线的长度。1英寸=2.54cm
  • 屏幕分辨率:屏幕横纵方向上的像素点数。1px = 1个像素点
  • 屏幕像素密度:每英寸上的像素点数。(dpi:dot per inch) eg: 5英寸,1280*1080p,dpi = √(1280^2+1080^2) / 5

  • 密度无关像素:dp(density independent pixels),160dpi为基准,1px = 1dp

  • sp(scale independent pixels): 推荐使用12 14 18 22

尽可能的使用相对布局,match_parent,wrap_content,weigth等属性

  • weight = 原始宽度(设置的width值) + 剩余空间所占百分比的宽度(总的宽度-所有控件的宽度)
1
2
3
4
5
6
7
8
9
10
11
12
<LinearLayout android:orientation="vertical" ...>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:weight="1"
android:text="btn1">

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:weight="2"
android:text="btn2">

</LinearLayout>

btn1_width = 0 + (L-0-0) 1/3 = 1/3L
btn2_width = 0 + (L-0-0)
2/3 = 2/3L

1
2
3
4
5
6
7
8
9
10
11
12
<LinearLayout android:orientation="vertical" ...>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weight="1"
android:text="btn1">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weight="2"
android:text="btn2">

</LinearLayout>

btn1_width = L + (L-L-L) 1/3 = 2/3L
btn2_width = L + (L-L-L)
2/3 = 1/3L

使用限定符

  • 小屏幕,单面板 res/layout/main.xml
  • 大屏幕,双面板(version<3.2) res/layout-large/main.xml
  • 大屏幕,双面板(version>3.2) res/layout-sw600dp/main.xml

由于上面大屏幕两个xml维护的布局一样,所有可以使用别名

1
2
res/layout/main.xml
res/layout/main_twopanes.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- res/values/layout.xml
<resources>
<item name="main" type="layout">@layout/main</item>
<bool name="has_two_panes">false</bool>
</resources>

- version<3.2 res/values-large/layout.xml
<resources>

<item name="main" type="layout">@layout/main_twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>

- version>3.2 res/layout-sw600dp/layout.xml
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>

1
2
// 使用别名
setContentView(R.layout.main)

屏幕方向限定符

res/values-sw600dp-land/layouts.xml
res/values-sw600dp-port/layouts.xml

为个分辨率的尺寸,建立一个文件标准

  • 在values-xx目录下,建立相应的标准,使用像素px。默认在values下建立一套缺省的,防治未创建values-xx尺寸的手机崩溃。

Hongyang Android 屏幕适配方案

android-percent-support-lib-sample

.9 图片

  • 左上,代表可拉伸的区域
  • 右下,代表内容可以填充的区域,底部划线距离两边的距离分别代表内容的paddingLeft,paddingRight,右侧划线距离两边的距离分别代表内容的paddingTop,paddingBottom

图片准备

一般先准备分辨率较大的图片
如果只有一套图,放在xxdpi目录下,占用的内存相对较小