您的位置:首页 > 其它

[置顶] 监听软键盘打开或关闭触发动作

2016-12-19 20:14 423 查看
/**

* Created by chaoren on 2016/12/13.

* 软键盘关闭,打开监听工具类,文章下面有使用方法

*/

public class SoftKeyboardStateHelper implements ViewTreeObserver.OnGlobalLayoutListener {

public interface SoftKeyboardStateListener {

void onSoftKeyboardOpened(int keyboardHeightInPx);

void onSoftKeyboardClosed();
}

private final List<SoftKeyboardStateListener> listeners = new LinkedList<SoftKeyboardStateListener>();
private final View activityRootView;
private int lastSoftKeyboardHeightInPx;
private boolean isSoftKeyboardOpened;

public SoftKeyboardStateHelper(View activityRootView) {
this(activityRootView, false);
}

public SoftKeyboardStateHelper(View activityRootView, boolean isSoftKeyboardOpened) {
this.activityRootView = activityRootView;
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}

@Override
public void onGlobalLayout() {
final Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);

final int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (!isSoftKeyboardOpened && heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
isSoftKeyboardOpened = true;
notifyOnSoftKeyboardOpened(heightDiff);
} else if (isSoftKeyboardOpened && heightDiff < 100) {
isSoftKeyboardOpened = false;
notifyOnSoftKeyboardClosed();
}
}

public void setIsSoftKeyboardOpened(boolean isSoftKeyboardOpened) {
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
}

public boolean isSoftKeyboardOpened() {
return isSoftKeyboardOpened;
}

public int getLastSoftKeyboardHeightInPx() {
return lastSoftKeyboardHeightInPx;
}

public void addSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.add(listener);
}

public void removeSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.remove(listener);
}

private void notifyOnSoftKeyboardOpened(int keyboardHeightInPx) {
this.lastSoftKeyboardHeightInPx = keyboardHeightInPx;

for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardOpened(keyboardHeightInPx);
}
}
}

private void notifyOnSoftKeyboardClosed() {
for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardClosed();
}
}
}


}
/**

*下面是使用方法

/

final SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(findViewById(R.id.edittext_money));

softKeyboardStateHelper.addSoftKeyboardStateListener(this);

//回调

//打开软键盘触发的方法

@Override

public void onSoftKeyboardOpened(int keyboardHeightInPx) {

}


//关闭软键盘触发的方法

@Override

public void onSoftKeyboardClosed() {

     }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: