当屏幕足够高但不包括短屏幕上的图像时,我想创建一个动态登录屏幕,其中包含装饰性品牌图像。当键盘出现时,可能需要删除图像。当键盘被隐藏时,图像可以回来。
对于网页,我只需对设备高度使用 CSS 媒体查询,适当地显示或隐藏图像,这一切都会很好地工作。我认为 Android 视图不可能有任何简单和干净的东西,是吗?所以我想我需要知道创建活动时窗口的高度并适当地创建视图。
在清单中,我将我的主要活动设置adjustResize
为键盘出现的时间。当键盘出现时,我的视图确实会调整大小,但令人惊讶的是我的活动没有重新创建。当屏幕旋转时,将重新创建活动。
文档说,当键盘可用性发生变化时,将重新创建视图。第一段来自https://developer.android.com/guide/topics/resources/runtime-changes
某些设备配置可能会在运行时更改(例如屏幕方向、键盘可用性以及用户启用多窗口模式时)。当发生这种变化时,Android 会重新启动正在运行的 Activity(调用 onDestroy(),然后调用 onCreate())。重新启动行为旨在通过使用与新设备配置匹配的替代资源自动重新加载您的应用程序来帮助您的应用程序适应新配置。
我的问题是
处理我的设计目标的最佳方式是什么?
为什么键盘出现时我的活动没有重新创建?
以下是我的测试应用程序的相关部分。这没有图像,因为在遇到与文档相矛盾的行为之前,我什至没有走得那么远。
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("MainActivity", "onCreate")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="Top"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="@color/colorAccent" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/intro"
android:singleLine="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="Bottom"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:background="@color/colorAccent" />
</android.support.constraint.ConstraintLayout>