天天看点

Android 软键盘顶起布局相关

原文链接:http://blog.csdn.net/mr_liu_gege/article/details/53169359

拾人牙慧,感谢博主分享。试验了一下,确实有效果,收藏学习。

第一种情况:被键盘遮住的按钮没有位于布局的底部

代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width= "match_parent"
  4. android:layout_height= "wrap_content"
  5. android:orientation= "vertical"
  6. android:id= "@+id/parent_ll">
  7. <EditText
  8. android:id= "@+id/username"
  9. android:layout_width= "match_parent"
  10. android:layout_height= "wrap_content"
  11. android:layout_marginTop= "200dp"
  12. android:ems= "10" >
  13. </EditText>
  14. <EditText
  15. android:id= "@+id/userpwd"
  16. android:layout_width= "match_parent"
  17. android:layout_height= "wrap_content"
  18. android:layout_marginTop= "30dp"
  19. android:ems= "10"
  20. android:inputType= "textPassword" />
  21. <Button
  22. android:id= "@+id/btn"
  23. android:layout_width= "wrap_content"
  24. android:layout_height= "wrap_content"
  25. android:layout_gravity= "center"
  26. android:layout_marginTop= "30dp"
  27. android:text= "Button" />
  28. </LinearLayout>
  1. public class MainActivity extends Activity {
  2. private Button btn;
  3. private LinearLayout parent_ll;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.layout_login);
  8. /*ScrollView mScrollView = (ScrollView)findViewById(R.id.scrollContent);
  9. mScrollView.setVerticalScrollBarEnabled(false);
  10. mScrollView.setHorizontalScrollBarEnabled(false);*/
  11. parent_ll=(LinearLayout) findViewById(R.id.parent_ll);
  12. btn=(Button) findViewById(R.id.btn);
  13. addLayoutListener(parent_ll, btn);
  14. }
  15. /**
  16. * 1、获取parentView在窗体的可视区域
  17. * 2、获取parentView在窗体的不可视区域高度
  18. * 3、判断不可视区域高度
  19. * 1、大于100:键盘显示 获取childView的窗体坐标
  20. * 算出parentView需要滚动的高度,使childView显示。
  21. * 2、小于100:键盘隐藏
  22. *
  23. * @param parentView 根布局
  24. * @param childView 需要显示的最下方View
  25. */
  26. public void addLayoutListener(final View parentView, final View childView) {
  27. parentView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() {
  28. @Override
  29. public void onGlobalLayout() {
  30. Rect rect = new Rect();
  31. parentView.getWindowVisibleDisplayFrame(rect);
  32. int mainInvisibleHeight = parentView.getRootView().getHeight() - rect.bottom;
  33. if (mainInvisibleHeight > ) {
  34. int[] location = new int[ ];
  35. childView.getLocationInWindow(location);
  36. int srollHeight = (location[ ] + childView.getHeight()) - rect.bottom;
  37. parentView.scrollTo( , srollHeight);
  38. } else {
  39. parentView.scrollTo( , );
  40. }
  41. }
  42. });
  43. }
  44. }

addLayoutListener() 这个方法是关键。

第二种情况:被键盘遮住的按钮位于布局的底部

父布局需要是Relativelayout,按钮需要alignParentBottom,可能清单文件还需要设置android:windowSoftInputMode