在软键盘上显示 Toast 消息

默认情况下,即使键盘显示,Android 也会在屏幕底部显示 Toast 消息。这将在键盘上方显示 Toast 消息。

public void showMessage(final String message, final int length) {
    View root = findViewById(android.R.id.content);
    Toast toast = Toast.makeText(this, message, length);
    int yOffset = Math.max(0, root.getHeight() - toast.getYOffset());
    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, yOffset);
    toast.show();
}