Android屏幕分辨率适配

Android屏幕分辨率适配一般有三种方案:

  1. 通过百分比的形式进行布局
  2. 动态适配屏幕分辨率,通过一系列算法去计算每个view在用户手机屏幕中应该的宽高,从而达到一个适配效果;
  3. 静态适配屏幕分辨率,就是通过工具生成各种屏幕尺寸的xml文件。

ConstraintLayout进行百分比布局

ConstraintLayout中,当子View尺寸设置为MATCH_CONSTRAINT(0dp)时,默认行为是占据所有可用空间,但是可以通过layout_constraintHeight_percentlayout_constraintWidth_percent来设置为占用父View的百分比,注意,这个百分比是整个父View的宽高的百分比,而不是可用空间的百分比。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#00eeee"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent=".5"
app:layout_constraintWidth_percent=".5"/>
</androidx.constraintlayout.widget.ConstraintLayout>

通过bias来设置位置偏移,下面用法可以让子View左边与parent的间距占比为20%,而不是默认的50%。详细介绍可参考Centering positioning and bias

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/test_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#00eeee"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintVertical_bias="0.2"/>
</androidx.constraintlayout.widget.ConstraintLayout>

静态屏幕适配

通过AndroidStudio的ScreenMatch插件生成不同分辨率的dimens资源文件来进行适配。该插件会基于res/values/dimens.xml生成不同分辨率的比如:

1
2
3
4
5
6
7
8
res/values-sw240dp/dimens.xml
res/values-sw320dp/dimens.xml
res/values-sw384dp/dimens.xml
res/values-sw392dp/dimens.xml
res/values-sw400dp/dimens.xml
res/values-sw410dp/dimens.xml
res/values-sw411dp/dimens.xml
res/values-sw432dp/dimens.xml

其中sw240dp值得是最小宽度限定符,即屏幕可用高度和宽度中最小尺寸的dp值。比如Pixel 6设备,分辨率是1080x2400,像素密度是420dpi,density=420/160=2.625,对应的dp是1080/2.625=411,所以使用的是res/values-sw411dp/dimens.xml

参考:Android屏幕适配总结

参考