在軟鍵盤上顯示 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();
}