在Android 11中,WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE被废弃了,官方推荐使用新的WindowInsetsAnimation.Callback来实现类似的效果。下面是一个示例代码,演示如何使用WindowInsetsAnimation.Callback来调整布局以适应软键盘的显示和隐藏。
首先,在你的Activity或Fragment中创建一个WindowInsetsAnimation.Callback的实例,并重写onProgress方法来调整布局:
class MyWindowInsetsAnimationCallback extends WindowInsetsAnimation.Callback {
private final View mView;
public MyWindowInsetsAnimationCallback(View view) {
mView = view;
}
@Override
public void onProgress(WindowInsetsAnimation animation, List insets, List rects) {
super.onProgress(animation, insets, rects);
// 获取显示区域的矩形
Rect visibleRect = new Rect();
mView.getWindowVisibleDisplayFrame(visibleRect);
// 获取窗口的Insets
WindowInsets windowInsets = insets.get(insets.size() - 1);
// 获取软键盘的可见高度
int keyboardHeight = windowInsets.getInsets(WindowInsets.Type.ime()).bottom;
// 调整布局以适应软键盘
int bottomInset = windowInsets.getInsets(WindowInsets.Type.systemBars()).bottom;
mView.setPadding(0, 0, 0, keyboardHeight - bottomInset);
}
}
然后,在你的Activity或Fragment的onCreate方法中设置WindowInsetsAnimation.Callback:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View rootView = findViewById(R.id.root_view);
// 创建WindowInsetsAnimation.Callback实例
MyWindowInsetsAnimationCallback animationCallback = new MyWindowInsetsAnimationCallback(rootView);
// 设置WindowInsetsController,并设置WindowInsetsAnimation.Callback
WindowInsetsController controller = rootView.getWindowInsetsController();
controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
controller.registerAnimationCallback(animationCallback);
}
这样,当软键盘显示或隐藏时,onProgress方法将被调用,你可以在该方法中根据软键盘的可见高度来调整布局以适应软键盘。
需要注意的是,在Android 11之前的版本中,可以使用WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE来实现类似的效果。因此,你可能需要在代码中进行版本判断,以便在不同的Android版本上使用适当的方法。