Android 키보드 올림 내림 상태확인

2020. 5. 25. 15:02Android

반응형

AndroidManifest.xml에서 android:windowSoftInputMode  adjustResize 속성을 추가

 

SoftKeyboardDectectorView 클래스 생성

 

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
 
public class SoftKeyboardDectectorView extends View {
 
    private boolean mShownKeyboard;
    private OnShownKeyboardListener mOnShownSoftKeyboard;
    private OnHiddenKeyboardListener onHiddenSoftKeyboard;
 
    public SoftKeyboardDectectorView(Context context) {
        this(context, null);
    }
 
    public SoftKeyboardDectectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Activity activity = (Activity)getContext();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        int diffHeight = (screenHeight - statusBarHeight) - h;
        if (diffHeight > 100 && !mShownKeyboard) { // 모든 키보드는 100px보다 크다고 가정
            mShownKeyboard = true;
            onShownSoftKeyboard();
        } else if (diffHeight < 100 && mShownKeyboard) {
            mShownKeyboard = false;
            onHiddenSoftKeyboard();
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }
 
    public void onHiddenSoftKeyboard() {
        if (onHiddenSoftKeyboard != null)
            onHiddenSoftKeyboard.onHiddenSoftKeyboard();
    }
 
    public void onShownSoftKeyboard() {
        if (mOnShownSoftKeyboard != null)
            mOnShownSoftKeyboard.onShowSoftKeyboard();
    }
 
    public void setOnShownKeyboard(OnShownKeyboardListener listener) {
        mOnShownSoftKeyboard = listener;
    }
 
    public void setOnHiddenKeyboard(OnHiddenKeyboardListener listener) {
        onHiddenSoftKeyboard = listener;
    }
 
    public interface OnShownKeyboardListener {
        public void onShowSoftKeyboard();
    }
 
    public interface OnHiddenKeyboardListener {
        public void onHiddenSoftKeyboard();
    }
}

 

사용법

final SoftKeyboardDectectorView softKeyboardDecector = new SoftKeyboardDectectorView(this);
addContentView(softKeyboardDecector, new FrameLayout.LayoutParams(-1, -1));
 
softKeyboardDecector.setOnShownKeyboard(new OnShownKeyboardListener() {
 
    @Override
    public void onShowSoftKeyboard() {
        //키보드 등장할 때
    }
});
 
softKeyboardDecector.setOnHiddenKeyboard(new OnHiddenKeyboardListener() {
 
    @Override
    public void onHiddenSoftKeyboard() {
        // 키보드 사라질 때
    }
});


출처: https://givenjazz.tistory.com/54 [GivenJazz]

 

반응형