FAB在编辑文本点击时响应,FAB拿出键盘

FAB responded when edit text click, FAB comes up with keyboard

我正在使用 Google 的新设计支持库中的 FAB。我有一个长表格和一个 FAB 的屏幕。我希望 FAB 在软键盘打开时消失。找不到检测软键盘打开的方法。还有其他选择吗

我无法将侦听器设置为 EditText,因为它们都包含在不同的 Fragment 中,并且焦点更改侦听器在另一个 Fragment 中不可用。

我已经在 main Activity 中实现了 FAB,所以我无法为 EditText 焦点侦听器隐藏键盘侦听器,任何人都可以与我分享解决方案。

无法直接知道软键盘何时打开,但您可以执行以下操作:

contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {

    Rect r = new Rect();
    contentView.getWindowVisibleDisplayFrame(r);
    int screenHeight = contentView.getRootView().getHeight();

    // r.bottom is the position above soft keypad or device button.
    // if keypad is shown, the r.bottom is smaller than that before.
    int keypadHeight = screenHeight - r.bottom;

    if (keypadHeight > screenHeight * 0.15) {
        // keyboard is opened
        // Hide your FAB here
    }
    else {
        // keyboard is closed
    }
}
});

您可以监听键盘的打开和关闭。

public class BaseActivity extends Activity {
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
        int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(BaseActivity.this);

        if(heightDiff <= contentViewTop){
            onHideKeyboard();

            Intent intent = new Intent("KeyboardWillHide");
            broadcastManager.sendBroadcast(intent);
        } else {
            int keyboardHeight = heightDiff - contentViewTop;
            onShowKeyboard(keyboardHeight);

            Intent intent = new Intent("KeyboardWillShow");
            intent.putExtra("KeyboardHeight", keyboardHeight);
            broadcastManager.sendBroadcast(intent);
        }
    }
};

private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;

protected void onShowKeyboard(int keyboardHeight) {}
protected void onHideKeyboard() {}

protected void attachKeyboardListeners() {
    if (keyboardListenersAttached) {
        return;
    }

    rootLayout = (ViewGroup) findViewById(R.id.rootLayout);
    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

    keyboardListenersAttached = true;
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (keyboardListenersAttached) {
        rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
    }
}
}

这个问题中列出了更详细的示例:SoftKeyboard open and close listener in an activity in Android?