鍵盤升起避免遮擋佈局

本文介紹了在任意佈局中鍵盤升起避免某按鈕或某任意控件被遮擋的方法,主要用到了addOnGlobalLayoutListener方法——注:如果要解決webview中鍵盤遮擋輸入框問題請參考如下博文:http://blog.csdn.net/qiuyin2015/article/details/53156626
使用下面的controlKeyboardLayout()方法不但可以避免控件被遮擋也可以用來判斷鍵盤升起事件——只要rootInvisibleHeight >100即可視爲鍵盤升起,只要在後面添加自己的相應處理就行。

話不多說直接上源碼:

1. MainActivity
public class MainActivity extends Activity {
    private LinearLayout mRoot;
    private Button mSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRoot = (LinearLayout) findViewById(R.id.root);
        mSubmit = (Button) findViewById(R.id.submit);

        //調用下面方法可以避免鍵盤遮擋
        controlKeyboardLayout(mRoot, mSubmit);
    }

    /**
     * @param root 最外層佈局,需要調整的佈局
     * @param scrollToView 被鍵盤遮擋的scrollToView,滾動root,使scrollToView在root可視區域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //獲取root在窗體的可視區域
                root.getWindowVisibleDisplayFrame(rect);
                //獲取root在窗體的不可視區域高度(被其他View遮擋的區域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可視區域高度大於100,則鍵盤顯示
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    //獲取scrollToView在窗體的座標
                    scrollToView.getLocationInWindow(location);
                    //計算root滾動高度,使scrollToView在可見區域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //鍵盤隱藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }

}

2. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_vertical" >

    <EditText android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:hint="edit1"/>
    <EditText android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:hint="edit2"/>
    <EditText android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:hint="edit3"/>
    <Button android:id="@+id/submit"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:text="submit"/>

</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章