點選EditText的時候出現被鍵盤遮擋 在不使用scrollView的情況

無道之崛起發表於2020-11-27
public class KeyboardPatch {
    private Activity activity;
    private View decorView;
    private View contentView;
    private EditText editText;

    /**
     * 建構函式
     *
     * @param contentView 介面根佈局,
     */
    public KeyboardPatch(Activity activity, View contentView) {
        this.activity = activity;
        this.decorView = activity.getWindow().getDecorView();
        this.contentView = contentView;
    }

    /**
     * 監聽layout變化
     */
    public void enable() {
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
        }
    }

    /**
     * 取消監聽
     */
    public void disable() {
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
        }
    }


    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            decorView.getWindowVisibleDisplayFrame(r);
            int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
            int diff = height - r.bottom;
            if (diff > 100) {
                Log.d("Tag", "抬起鍵盤" + diff + "------screen=" + height);
                change(diff, height);
            } else {
                Log.d("Tag", "關閉鍵盤" + diff + "------screen=" + height);
                change(0, height);
            }
        }
    };

    public void setEditTextView(EditText editText) {
        this.editText = editText;
    }

    private void change(int diff, int screenHeight) {
        if (diff > 0) {
            int[] location = new int[2];
            editText.getLocationInWindow(location);
            int visiHeight = screenHeight - diff;//螢幕的高度——鍵盤的高度 ==可視高度
            int local = location[1];//editText的高度 top--y
            int editBottomHeight = local + editText.getHeight();//view的底部的高度
            if (editBottomHeight > visiHeight) {//如果底部的高度大於 可見的高度 說明遮擋 往上移動
                contentView.setPadding(0, visiHeight - editBottomHeight, 0, 0);
            }
        } else {
            contentView.setPadding(0, 0, 0, 0);
        }
    }

}

 

 

//使用

var keyboard: KeyboardPatch? = null

edit_.setOnFocusChangeListener { v, hasFocus ->
    if (hasFocus) {
        keyboard?.enable()
        keyboard?.setEditTextView(edit_)
    } else {
       keyboard?.disable()
    }

}

keyboard= KeyboardPatch(this, "根佈局")

相關文章