/**
* @param root 最外层布局,需要调整的布局
* @param scrollToView 被键盘遮挡的scrollToView,滚动root,使scrollToView在root可视区域的底部
*/
private void listenKeyboardLayout(final LinearLayout root, final View scrollToView) {
SoftKeyboardStateHelper keyboardStateHelper = new SoftKeyboardStateHelper(root);
keyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateListener() {
@Override
public void onSoftKeyboardOpened(int keyboardHeightInPx) {
Rect rect = new Rect();
// 获取root在窗体的可视区域
root.getWindowVisibleDisplayFrame(rect);
int[] location = new int[2];
// 获取scrollToView在窗体的坐标
scrollToView.getLocationInWindow(location);
// 计算root滚动高度,使scrollToView在可见区域的底部
int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
root.scrollTo(0, srollHeight);
}
@Override
public void onSoftKeyboardClosed() {
// 键盘隐藏
root.scrollTo(0, 0);
}
});
}
在此要获取SoftKeyboardStateHelper类
效果图如下:
下面提供完整的代码及布局文件:
MainActivity
public class MainActivity extends Activity {
private LinearLayout mRoot;
private Button mSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRoot = (LinearLayout) findViewById(R.id.root);
mSubmit = (Button) findViewById(R.id.submit);
listenKeyboardLayout(root, mSubmit);
}
/**
* @param root 最外层布局,需要调整的布局
* @param scrollToView 被键盘遮挡的scrollToView,滚动root,使scrollToView在root可视区域的底
*/
private void listenKeyboardLayout(final LinearLayout root, final View scrollToView) {
SoftKeyboardStateHelper keyboardStateHelper = new SoftKeyboardStateHelper(root);
keyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateListener() {
@Override
public void onSoftKeyboardOpened(int keyboardHeightInPx) {
Rect rect = new Rect();
// 获取root在窗体的可视区域
root.getWindowVisibleDisplayFrame(rect);
int[] location = new int[2];
// 获取scrollToView在窗体的坐标
scrollToView.getLocationInWindow(location);
// 计算root滚动高度,使scrollToView在可见区域的底部
int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
root.scrollTo(0, srollHeight);
}
@Override
public void onSoftKeyboardClosed() {
// 键盘隐藏
root.scrollTo(0, 0);
}
});
}
activity_main.xml
android:id="@+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_vertical" >
android:layout_height="50dip"
android:hint="edit1"/>
android:layout_height="50dip"
android:hint="edit2"/>
android:layout_height="50dip"
android:hint="edit3"/>
android:layout_width="fill_parent"
android:layout_height="50dip"
android:text="submit"/>