原文連結: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