编辑于2016年10月13日
用户登陆大概是每一个项目最先遇到的需求,但有时UI界面的设计刚好使键盘弹起挡住登陆按钮,这多多少少让用户觉得麻烦。
QQ登陆的时候有一个效果,随着键盘的弹起,整个页面向上弹起,使软键盘刚好位于登陆按钮下方,方便了用户在输入账号密码后直接登陆。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:gravity="center"
android:hint="请输入账号"
android:textSize="18dp"
android:background="@drawable/input_login"/>
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:gravity="center"
android:inputType="textPassword"
android:hint="请输入密码"
android:textSize="18dp"
android:background="@drawable/input_login"/>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="@drawable/btn_login"
android:text="登录"
android:textColor="#ffffff"
android:textSize="18dp" />
</LinearLayout>
ll_login.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
private int[] location;
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
// 获取ll_login在窗体的可视区域
ll_login.getWindowVisibleDisplayFrame(rect);
// 获取ll_login在窗体的不可视区域高度(被其他View遮挡的区域高度)
int rootInvisibleHeight = ll_login.getRootView().getHeight() - rect.bottom;
// 键盘显示
if (rootInvisibleHeight > 100) {
//只记录btn_login位置未变化时的位置
if (location==null){
location = new int[2];
// 获取btn_login在窗体的坐标
btn_login.getLocationInWindow(location);
}
// 计算ll_login滚动高度,使btn_login在可见区域
int srollHeight = location[1] + btn_login.getHeight() - rect.bottom;
ll_login.scrollTo(0, srollHeight);
} else {
// 键盘隐藏
ll_login.scrollTo(0, 0);
}
}
});
最终版本