Androidでパスワード入力ダイアログを表示するには、AlertDialog とカスタムのレイアウトを組み合わせる方法が簡単で実用的です。以下のステップで実現できます。
ステップ 1: カスタムレイアウトを作成
レイアウトXMLファイル(例: dialog_password_input.xml)を用意し、EditText をパスワード入力フィールドとして使用します。
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter password"
android:inputType="textPassword" />
</LinearLayout>
ステップ 2: ダイアログを作成
AlertDialog.Builder を使用してダイアログを作成し、上記のカスタムレイアウトを設定します。
以下は、Javaでのコード例です。
java
public void showPasswordDialog(Context context) {
// カスタムレイアウトをインフレート
LayoutInflater inflater = LayoutInflater.from(context);
View dialogView = inflater.inflate(R.layout.dialog_password_input, null);
// EditText を取得
EditText passwordEditText = dialogView.findViewById(R.id.passwordEditText);
// ダイアログを構築
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Password Required");
builder.setView(dialogView);
builder.setPositiveButton("OK", (dialog, which) -> {
// 入力されたパスワードを取得
String password = passwordEditText.getText().toString();
if (!password.isEmpty()) {
// 入力されたパスワードを処理
Log.d("PasswordDialog", "Password: " + password);
} else {
Log.d("PasswordDialog", "No password entered.");
}
});
builder.setNegativeButton("Cancel", (dialog, which) -> {
// キャンセルボタンの処理
dialog.dismiss();
});
// ダイアログを表示
AlertDialog dialog = builder.create();
dialog.show();
}
ステップ 3: ダイアログを表示
上記の showPasswordDialog() メソッドを必要な場所で呼び出します。たとえば、ボタンのクリックイベントなどから呼び出すことができます。
java
button.setOnClickListener(v -> showPasswordDialog(this));
主なポイント
- カスタムレイアウト: レイアウトの柔軟性を確保し、パスワード入力用の
EditTextを作成。 - 入力タイプ:
android:inputType="textPassword"を指定することで、入力がパスワード形式になります。 - ボタンのリスナー: OK ボタンでの入力値取得と Cancel ボタンでの動作を設定。



コメント