天天看點

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