Android API 33新特性:全面支持Foldable设备

发布时间:2023-12-08

Android API 33新特性:全面支持Foldable设备

更新:2023-05-14 06:44 Android API 33作为Android操作系统的最新版本,有一项全新的重大特性——全面支持Foldable设备。Foldable设备是指可折叠屏幕的Android设备,诸如三星Galaxy Fold、华为Mate X等。这些设备拥有一种新奇的使用方式,同时也带来了很多难题。Android API 33的全面支持,意味着应用开发者可以更好地为Foldable设备设计和开发应用程序。

一、折叠屏幕的适配方式

安卓API 33为折叠屏幕的适配提供了以下两种方式。

1、多窗口

在折叠设备中,应用可以同时在多个窗口中运行。可以通过setLaunchWindowingMode()方法来指定应用的窗口模式。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (resources.configuration.isFolded) { 
        setLaunchWindowingMode(ActivityInfo.WindowingMode.MULTI_WINDOW)
    }
}

2、窗口间联动

通过Activity.setWindowLayoutInfo() API可以创建一个窗口联动的XML文件,用于确保窗口在使用移动方式时保持同步。窗口联动功能可以让用户更加方便地同时操作多个窗口,在配置文件中定义好活动视图布局,就可以实现在折叠设备上的窗口联动。

<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <target android:name="com.example.app.ui.DetailActivity">
        <bounds android:left="0.18055555" android:right="0.75" android:top="0.2" android:bottom="0.8" />
    </target>
    <target android:name="com.example.app.ui.ListActivity">
        <bounds android:left="0.0" android:right="0.175" android:top="0.2" android:bottom="0.8" />
    </target>
</transition>

二、折叠式键盘

所有Foldable设备都拥有专用键盘,对于开发人员来说,这对于UI的设计提出了新要求。Android API 33针对Foldable设备的键盘特性,提供了FoldableKeyboardSensor类,允许应用程序知道设备是否在折叠或展开状态。开发者可以使用它来更新应用的UI,使其更适合当前的键盘状态。

fun showHidePassword(displayPassword: Boolean) {
    isPasswordVisible = displayPassword
    inputType = InputType.TYPE_CLASS_TEXT +
        (if (isPasswordVisible) InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD else InputType.TYPE_TEXT_VARIATION_PASSWORD)
}
val sensor = FoldableKeyboardSensor(this)
sensor.onChange { display: Boolean, _: Int, _: Int, _: FloatArray, _: Int ->
    showHidePassword(display)
}

三、屏幕分层支持

Android API 33支持折叠设备的屏幕分层特性。在横向模式下,屏幕可以分成多个Panel类型,每个Panel在折叠和展开时都有不同的显示方式。利用这种分层模式,开发者可以更好地创建适合屏幕尺寸的应用。

<FrameLayout>
    <LinearLayout>
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <com.google.android.material.bottomsheet.BottomSheetBehavior>
        <LinearLayout>
            <Button
                android:id="@+id/confirm"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <Button
                android:id="@+id/cancel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </com.google.android.material.bottomsheet.BottomSheetBehavior>
</FrameLayout>

结尾

Android API 33的全面支持Foldable设备,为Android应用开发者带来了很多新的机遇。借助于这些新特性,我们将可以更好地创建出适合Foldable设备的应用,为用户带来全新的体验。