在AndroidManifest.xml文件中添加以下属性:
其中,android:configChanges用于指定当键盘隐藏、屏幕方向或屏幕大小发生变化时不重新创建Activity,而是保留其原有状态;android:windowSoftInputMode用于指定如何调整窗口以使键盘不会遮挡输入框。
在布局文件中添加以下属性:
其中,ScrollView用于实现滚动效果,LinearLayout用于放置输入框等UI组件。
最后,在Activity中添加以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
// 监听键盘变化
final View activityRootView = findViewById(R.id.activity_root_view);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int screenHeight = activityRootView.getRootView().getHeight();
int heightDifference = screenHeight - (r.bottom - r.top);
if (heightDifference > 100) {
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.scrollTo(0, linearLayout.getHeight());
}
});
}
}
});
}
其中,activityRootView是布局文件中顶层的视图,getHeight()方法用于获取其高度;getWindowVisibleDisplayFrame()用于获取屏幕可视区域大小;post()方法用于在UI线程中执行滚动操作。这段代码的作用是在键盘弹出时自