在我的应用程序中,我使用单个活动 - 具有多个片段的 MainActivity。在清单文件中,我将活动的 windowSoftInputMode 设置为 adjustmentResize,因为我需要在显示键盘的大多数片段中执行此行为。
<activity
android:name=".main.MainActivity"
android:configChanges="orientation|screenSize|layoutDirection"
android:exported="true"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" />
但是,根据设计,有几个页面在显示键盘时不需要调整大小行为。因此,我将 onCreateView
中的 softInputMode 设置为
SOFT_INPUT_ADJUST_NOTHING,并在
onDestroyView
中设置回 SOFT_INPUT_ADJUST_RESIZE。
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
return inflater.inflate(R.layout.fragment_b, container, false)
}
override fun onDestroyView() {
activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
}
一切正常,但现在我收到 SOFT_INPUT_ADJUST_RESIZE 的弃用警告,并建议将
setDecorFitsSystemWindows
与 OnApplyWindowInsetsListener
一起使用。这个解决方案让我很困惑,因为我不明白为什么我们需要 setDecorFitsSystemWindows,我相信它设置应用程序的内容是否可以绘制在状态栏和导航栏后面,并且最终结果是与初始单行相比更多行代码接近。
如果有人可以帮助我更新代码以保持应用程序的行为与以前相同,但迁移到使用新的 api,我将不胜感激。
// In your activity's onCreate or onViewCreated method
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the root view of your activity
val rootView = findViewById<View>(android.R.id.content)
// Apply the new insets behavior using OnApplyWindowInsetsListener
ViewCompat.setOnApplyWindowInsetsListener(rootView) { view, insets ->
val params = view.layoutParams as ViewGroup.MarginLayoutParams
params.bottomMargin = insets.systemWindowInsetBottom // Adjust bottom margin based on keyboard height
insets
}
// Set the decor to fit system windows to handle insets properly
ViewCompat.setDecorFitsSystemWindows(window, true)
}