解決軟鍵盤彈出遮擋button

分類:技術 時間:2017-01-13

在一般登錄界面,軟鍵盤彈出時會遮擋登錄按鈕,網上的解決方法一般都是設置WindowSoftInputMode和scrollview嵌套,但無法達到我想要的效果。

下面這種方法能夠解決:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        addLayoutListener(rootView, bottomView);
    }
/**
     * @param rootView 根布局
     * @param bottomView 需要顯示的最下方View,
     */
    public void addLayoutListener(View rootView, View bottomView) {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -gt; {
            Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);//獲取rootView的可視區域
            int invisibleHeight = rootView.getRootView().getHeight() - rect.bottom;//獲取rootView的不可視區域高度
            if (invisibleHeight gt; 150) { //鍵盤顯示 
                int[] location = new int[2];
                bottomView.getLocationInWindow(location); //獲取bottomView的坐標
                int scrollHeight = (location[1]   bottomView.getHeight()) - rect.bottom;//算出需要滾動的高度
                if (scrollHeight != 0) {//防止界面元素改變調用監聽,使界面上下跳動,如驗證碼倒計時
                    rootView.scrollTo(0, scrollHeight);
                }
            } else {
                rootView.scrollTo(0, 0);
            }
        });
    }

Tags: 安卓開發

文章來源:http://www.jianshu.com/p/733759fd87bf


ads
ads

相關文章
ads

相關文章

ad