XML 中以 android:hint 設定佔位文字,程式碼中同樣簡單:呼叫 setHint(CharSequence) 即可。無需複雜容器包裝,原問題碼誤以為需 FrameLayout 包裝才能設定。
// 建立 EditText
EditText editText = new EditText(this);
editText.setHint("請輸入姓名"); // 設定 placeholder/hint
editText.setHintTextColor(Color.GRAY); // 可選:設定 hint 顏色
// 加入 AlertDialog
new AlertDialog.Builder(this)
.setTitle("輸入資訊")
.setView(editText)
.setPositiveButton("確定", (dialog, which) -> {
String input = editText.getText().toString();
// 處理輸入
})
.setNegativeButton("取消", null)
.show();
SpannableString hint = new SpannableString("請輸入手機號碼");
hint.setSpan(new ForegroundColorSpan(Color.RED), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
hint.setSpan(new StyleSpan(Typeface.ITALIC), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setHint(hint);
| XML 屬性 | 程式碼方法 | 說明 |
|---|---|---|
android:hint | setHint() | 佔位文字 |
android:textColorHint | setHintTextColor() | Hint 文字顏色 |
android:inputType | setInputType() | 輸入類型(文字、數字、密碼等) |
android:maxLines | setMaxLines() | 最大行數 |
android:imeOptions | setImeOptions() | 鍵盤動作鍵(搜尋、完成、下一個) |
public View createFormField(Context context, String label, String hint, int inputType) {
LinearLayout container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setPadding(24, 16, 24, 16);
TextView tvLabel = new TextView(context);
tvLabel.setText(label);
tvLabel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
tvLabel.setTextColor(Color.DKGRAY);
EditText et = new EditText(context);
et.setHint(hint);
et.setInputType(inputType);
et.setBackgroundResource(R.drawable.edittext_bg); // 自訂背景
container.addView(tvLabel);
container.addView(et);
return container;
}
// 使用
LinearLayout form = new LinearLayout(this);
form.setOrientation(LinearLayout.VERTICAL);
form.addView(createFormField(this, "姓名", "請輸入姓名", InputType.TYPE_CLASS_TEXT));
form.addView(createFormField(this, "電話", "請輸入電話", InputType.TYPE_CLASS_PHONE));
new AlertDialog.Builder(this)
.setTitle("完善資料")
.setView(form)
.show();
setHint 設定的是「空值時顯示的提示」,非預設值。若需預設值用 setText()。LayoutParams 需對應父容器類型(LinearLayout.LayoutParams、RelativeLayout.LayoutParams 等)。dialog.getWindow().setLayout(width, height) 調整。程式碼動態設定 Hint 只需一行 setHint(),配合 SpannableString 即可實現豐富樣式,無需額外容器包裝。