原文链接: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 > ) {
- int[] location = new int[ ];
- childView.getLocationInWindow(location);
- int srollHeight = (location[ ] + childView.getHeight()) - rect.bottom;
- parentView.scrollTo( , srollHeight);
- } else {
- parentView.scrollTo( , );
- }
- }
- });
- }
- }
addLayoutListener() 这个方法是关键。
第二种情况:被键盘遮住的按钮位于布局的底部
父布局需要是Relativelayout,按钮需要alignParentBottom,可能清单文件还需要设置android:windowSoftInputMode