原文链接:http://blog.csdn.net/mr_liu_gege/article/details/53169359
拾人牙慧,感谢博主分享。试验了一下,确实有效果,收藏学习。
代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/parent_ll">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:ems="10" >
</EditText>
<EditText
android:id="@+id/userpwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Button" />
</LinearLayout>
public class MainActivity extends Activity {
private Button btn;
private LinearLayout parent_ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login);
/*ScrollView mScrollView = (ScrollView)findViewById(R.id.scrollContent);
mScrollView.setVerticalScrollBarEnabled(false);
mScrollView.setHorizontalScrollBarEnabled(false);*/
parent_ll=(LinearLayout) findViewById(R.id.parent_ll);
btn=(Button) findViewById(R.id.btn);
addLayoutListener(parent_ll, btn);
}
/**
* 1、获取parentView在窗体的可视区域
* 2、获取parentView在窗体的不可视区域高度
* 3、判断不可视区域高度
* 1、大于100:键盘显示 获取childView的窗体坐标
* 算出parentView需要滚动的高度,使childView显示。
* 2、小于100:键盘隐藏
*
* @param parentView 根布局
* @param childView 需要显示的最下方View
*/
public void addLayoutListener(final View parentView, final View childView) {
parentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
parentView.getWindowVisibleDisplayFrame(rect);
int mainInvisibleHeight = parentView.getRootView().getHeight() - rect.bottom;
if (mainInvisibleHeight > 100) {
int[] location = new int[2];
childView.getLocationInWindow(location);
int srollHeight = (location[1] + childView.getHeight()) - rect.bottom;
parentView.scrollTo(0, srollHeight);
} else {
parentView.scrollTo(0, 0);
}
}
});
}
}
addLayoutListener() 这个方法是关键。