在 Android AlertDialog 中为 EditText 添加更大的边距
Add bigger margin to EditText in Android AlertDialog
我在 AlertDialog 中有一个 EditText。看起来像这样。
看看它在哪里说 tddjdjck 以及它是如何缩进很多的。这就是我想要的(我使用 setPadding
左右设置为 50),但我也希望它下面的蓝线也缩进。我该怎么做?
我使用的代码如下:
final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
final EditText input = new EditText(thisActivity);
input.setSingleLine();
input.setPadding(50, 0, 50, 0);
alert.setTitle("by...");
alert.setMessage("enter the name of the person who did:");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
谢谢
final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
final EditText input = new EditText(thisActivity);
input.setSingleLine();
FrameLayout container = new FrameLayout(thisActivity);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.leftMargin = getResources().getDimensionPixelSize(R.dimen.dialog_margin);
input.setLayoutParams(params);
container.addView(input);
alert.setTitle("by...");
alert.setMessage("test message");
alert.setView(container);
确保在 dimens.xml 资源文件中添加另一行,例如
<dimen name="dialog_margin">20dp</dimen>
您可以在 setView
方法中传递间距参数
alert.setView(view ,left_space , top_space , right_space , bottom_space);
所以,在你的情况下你可以试试这个
alert.setView(input , 50 ,0, 50 , 0);
这里是 Builder 设置 EditText 视图的 Kotlin 扩展函数。
val Float.toPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
fun AlertDialog.Builder.setEditText(editText: EditText): AlertDialog.Builder {
val container = FrameLayout(context)
container.addView(editText)
val containerParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT
)
val marginHorizontal = 48F
val marginTop = 16F
containerParams.topMargin = (marginTop / 2).toPx
containerParams.leftMargin = marginHorizontal.toInt()
containerParams.rightMargin = marginHorizontal.toInt()
container.layoutParams = containerParams
val superContainer = FrameLayout(context)
superContainer.addView(container)
setView(superContainer)
return this
}
用法示例
val editText = EditText(this)
AlertDialog.Builder(this)
.setTitle("Group Name")
.setEditText(editText)
.setPositiveButton("OK", { _: DialogInterface, _: Int ->
// Do your work with text here
val text = editText.text.toString()
Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
})
.setNegativeButton("Cancel", null)
.show()
结果
我做一个通用的单输入AlertDialog函数。代码不言自明。
Utils.java
public class Utils {
/**
* Convert dp to px value.
* -
* Source:
*/
public static int dpToPx(float dp, Resources resources) {
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics());
return (int) px;
}
/**
* Show an AlertDialog with a single input box.
*
* @param context Application context
* @param title Dialog title
* @param message Dialog input message/hint
* @param inputType InputType of EditText
* @param positiveBtnText Dialog positive button text
* @param negativeBtnText Dialog negative button text
* @param listener Dialog buttons click listener
*/
public static void showSingleInputDialog(
@NonNull Context context,
@NonNull String title,
@NonNull String message,
int inputType,
@NonNull String positiveBtnText,
@NonNull String negativeBtnText,
@NonNull final SingleInputDialogListener listener
) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
TextInputLayout textInputLayout = new TextInputLayout(context);
final EditText input = new EditText(context);
input.setSingleLine(true);
input.setInputType(inputType);
input.setHint(message);
FrameLayout container = new FrameLayout(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int left_margin = Utils.dpToPx(20, context.getResources());
int top_margin = Utils.dpToPx(10, context.getResources());
int right_margin = Utils.dpToPx(20, context.getResources());
int bottom_margin = Utils.dpToPx(4, context.getResources());
params.setMargins(left_margin, top_margin, right_margin, bottom_margin);
textInputLayout.setLayoutParams(params);
textInputLayout.addView(input);
container.addView(textInputLayout);
alert.setView(container);
alert.setPositiveButton(positiveBtnText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
listener.positiveCallback(input.getText().toString());
}
});
alert.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.negativeCallback();
}
});
alert.show();
}
}
SingleInputDialogListener.java
public interface SingleInputDialogListener {
void positiveCallback(String inputText);
void negativeCallback();
}
使用示例:
Utils.showSingleInputDialog(mContext,
"Password recovery",
"Your e-mail address",
InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS,
"Recover",
"Cancel",
new SingleInputDialogListener() {
@Override
public void positiveCallback(String inputText) {
Toast.makeText(mContext, inputText, Toast.LENGTH_SHORT).show();
}
@Override
public void negativeCallback() {
// ...
}
});
float paddingDp = 10f;
int paddingPx = 5;
paddingPx = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip,
paddingDp, activity.Resources.DisplayMetrics);
//alert dialog
adDialog.SetView(input, paddingPx, 5, paddingPx, 5);
试试这个下面的扩展
我为 xamarin android 做了这个,我希望这对 Java 也适用,只需稍加修改
public static AlertDialog ShowInputDialogue(this Activity activity, string title, string message, string txtValue, string dismissButtonText, string submitButtonText, Action<string> OnSubmit,bool TextInputType =false,bool isEdittable =true)
{
AlertDialog adDialog = null;
try
{
adDialog = new AlertDialog.Builder(activity).Create();
// Create TextView
EditText input = new EditText(activity);
input.ImeOptions = Android.Views.InputMethods.ImeAction.Done;
input.Enabled = isEdittable;
float paddingDp = 10f;
int paddingPx = 5;
if (!TextInputType)
{
input.SetBackgroundResource(Resource.Color.edit_text_shape);
input.InputType = Android.Text.InputTypes.ClassNumber | Android.Text.InputTypes.NumberFlagDecimal;
input.Text = txtValue;
//input.SetMaxLines(5);
//input.SetLines(5);
}
else
{
input.SetBackgroundResource(Resource.Color.edit_text_shape);
// Convert to pixels
paddingPx = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, paddingDp, activity.Resources.DisplayMetrics);
input.SetPadding(paddingPx, paddingPx, paddingPx, paddingPx);
input.Text = txtValue;
input.SetMaxLines(5);
input.SetLines(5);
}
//input.FocusChange += (object sender, View.FocusChangeEventArgs e) =>
//{
// // request a soft keyboard.
// InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
// if (e.HasFocus)
// imm.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.None);
//};
input.EditorAction += (s, e) =>
{
if (e.ActionId == ImeAction.Done)
{
adDialog.Hide();
adDialog.Cancel();
if (OnSubmit != null)
OnSubmit(input.Text);
}
};
//adDialog.Window.ClearFlags(WindowManagerFlags.NotFocusable | WindowManagerFlags.AltFocusableIm);
adDialog.SetTitle(title);
adDialog.SetMessage(message);
adDialog.SetView(input, paddingPx, 5, paddingPx, 5);
adDialog.SetButton(dismissButtonText, new EventHandler<DialogClickEventArgs>(
(s, args) =>
{
adDialog.Hide();
adDialog.Cancel();
View view = adDialog.CurrentFocus;
if (view != null)
{
InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
}));
adDialog.SetButton2(submitButtonText, new EventHandler<DialogClickEventArgs>(
(s, args) =>
{
if (OnSubmit != null)
OnSubmit(input.Text);
View view = adDialog.CurrentFocus;
if (view != null)
{
InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
}));
adDialog.Window.Attributes.WindowAnimations = Resource.Style.DialogAnimation_2;
adDialog.Show();
//input.RequestFocus();
SetDialogueTheme(activity, adDialog);
}
catch (Exception ex)
{
throw ex;
}
return adDialog;
}
在activity中的用法:
this.ShowInputDialogue("Title", "", "editetext notes", "Cancel", "Save", async (val) =>
{
try
{
//handle for save
}
catch (Exception ex)
{
}
}, true);
我在 AlertDialog 中有一个 EditText。看起来像这样。
看看它在哪里说 tddjdjck 以及它是如何缩进很多的。这就是我想要的(我使用 setPadding
左右设置为 50),但我也希望它下面的蓝线也缩进。我该怎么做?
我使用的代码如下:
final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
final EditText input = new EditText(thisActivity);
input.setSingleLine();
input.setPadding(50, 0, 50, 0);
alert.setTitle("by...");
alert.setMessage("enter the name of the person who did:");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
谢谢
final AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
final EditText input = new EditText(thisActivity);
input.setSingleLine();
FrameLayout container = new FrameLayout(thisActivity);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.leftMargin = getResources().getDimensionPixelSize(R.dimen.dialog_margin);
input.setLayoutParams(params);
container.addView(input);
alert.setTitle("by...");
alert.setMessage("test message");
alert.setView(container);
确保在 dimens.xml 资源文件中添加另一行,例如
<dimen name="dialog_margin">20dp</dimen>
您可以在 setView
方法中传递间距参数
alert.setView(view ,left_space , top_space , right_space , bottom_space);
所以,在你的情况下你可以试试这个
alert.setView(input , 50 ,0, 50 , 0);
这里是 Builder 设置 EditText 视图的 Kotlin 扩展函数。
val Float.toPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
fun AlertDialog.Builder.setEditText(editText: EditText): AlertDialog.Builder {
val container = FrameLayout(context)
container.addView(editText)
val containerParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT
)
val marginHorizontal = 48F
val marginTop = 16F
containerParams.topMargin = (marginTop / 2).toPx
containerParams.leftMargin = marginHorizontal.toInt()
containerParams.rightMargin = marginHorizontal.toInt()
container.layoutParams = containerParams
val superContainer = FrameLayout(context)
superContainer.addView(container)
setView(superContainer)
return this
}
用法示例
val editText = EditText(this)
AlertDialog.Builder(this)
.setTitle("Group Name")
.setEditText(editText)
.setPositiveButton("OK", { _: DialogInterface, _: Int ->
// Do your work with text here
val text = editText.text.toString()
Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
})
.setNegativeButton("Cancel", null)
.show()
结果
我做一个通用的单输入AlertDialog函数。代码不言自明。
Utils.java
public class Utils {
/**
* Convert dp to px value.
* -
* Source:
*/
public static int dpToPx(float dp, Resources resources) {
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics());
return (int) px;
}
/**
* Show an AlertDialog with a single input box.
*
* @param context Application context
* @param title Dialog title
* @param message Dialog input message/hint
* @param inputType InputType of EditText
* @param positiveBtnText Dialog positive button text
* @param negativeBtnText Dialog negative button text
* @param listener Dialog buttons click listener
*/
public static void showSingleInputDialog(
@NonNull Context context,
@NonNull String title,
@NonNull String message,
int inputType,
@NonNull String positiveBtnText,
@NonNull String negativeBtnText,
@NonNull final SingleInputDialogListener listener
) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
TextInputLayout textInputLayout = new TextInputLayout(context);
final EditText input = new EditText(context);
input.setSingleLine(true);
input.setInputType(inputType);
input.setHint(message);
FrameLayout container = new FrameLayout(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int left_margin = Utils.dpToPx(20, context.getResources());
int top_margin = Utils.dpToPx(10, context.getResources());
int right_margin = Utils.dpToPx(20, context.getResources());
int bottom_margin = Utils.dpToPx(4, context.getResources());
params.setMargins(left_margin, top_margin, right_margin, bottom_margin);
textInputLayout.setLayoutParams(params);
textInputLayout.addView(input);
container.addView(textInputLayout);
alert.setView(container);
alert.setPositiveButton(positiveBtnText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
listener.positiveCallback(input.getText().toString());
}
});
alert.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.negativeCallback();
}
});
alert.show();
}
}
SingleInputDialogListener.java
public interface SingleInputDialogListener {
void positiveCallback(String inputText);
void negativeCallback();
}
使用示例:
Utils.showSingleInputDialog(mContext,
"Password recovery",
"Your e-mail address",
InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS,
"Recover",
"Cancel",
new SingleInputDialogListener() {
@Override
public void positiveCallback(String inputText) {
Toast.makeText(mContext, inputText, Toast.LENGTH_SHORT).show();
}
@Override
public void negativeCallback() {
// ...
}
});
float paddingDp = 10f;
int paddingPx = 5;
paddingPx = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip,
paddingDp, activity.Resources.DisplayMetrics);
//alert dialog
adDialog.SetView(input, paddingPx, 5, paddingPx, 5);
试试这个下面的扩展 我为 xamarin android 做了这个,我希望这对 Java 也适用,只需稍加修改
public static AlertDialog ShowInputDialogue(this Activity activity, string title, string message, string txtValue, string dismissButtonText, string submitButtonText, Action<string> OnSubmit,bool TextInputType =false,bool isEdittable =true)
{
AlertDialog adDialog = null;
try
{
adDialog = new AlertDialog.Builder(activity).Create();
// Create TextView
EditText input = new EditText(activity);
input.ImeOptions = Android.Views.InputMethods.ImeAction.Done;
input.Enabled = isEdittable;
float paddingDp = 10f;
int paddingPx = 5;
if (!TextInputType)
{
input.SetBackgroundResource(Resource.Color.edit_text_shape);
input.InputType = Android.Text.InputTypes.ClassNumber | Android.Text.InputTypes.NumberFlagDecimal;
input.Text = txtValue;
//input.SetMaxLines(5);
//input.SetLines(5);
}
else
{
input.SetBackgroundResource(Resource.Color.edit_text_shape);
// Convert to pixels
paddingPx = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, paddingDp, activity.Resources.DisplayMetrics);
input.SetPadding(paddingPx, paddingPx, paddingPx, paddingPx);
input.Text = txtValue;
input.SetMaxLines(5);
input.SetLines(5);
}
//input.FocusChange += (object sender, View.FocusChangeEventArgs e) =>
//{
// // request a soft keyboard.
// InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
// if (e.HasFocus)
// imm.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.None);
//};
input.EditorAction += (s, e) =>
{
if (e.ActionId == ImeAction.Done)
{
adDialog.Hide();
adDialog.Cancel();
if (OnSubmit != null)
OnSubmit(input.Text);
}
};
//adDialog.Window.ClearFlags(WindowManagerFlags.NotFocusable | WindowManagerFlags.AltFocusableIm);
adDialog.SetTitle(title);
adDialog.SetMessage(message);
adDialog.SetView(input, paddingPx, 5, paddingPx, 5);
adDialog.SetButton(dismissButtonText, new EventHandler<DialogClickEventArgs>(
(s, args) =>
{
adDialog.Hide();
adDialog.Cancel();
View view = adDialog.CurrentFocus;
if (view != null)
{
InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
}));
adDialog.SetButton2(submitButtonText, new EventHandler<DialogClickEventArgs>(
(s, args) =>
{
if (OnSubmit != null)
OnSubmit(input.Text);
View view = adDialog.CurrentFocus;
if (view != null)
{
InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
}));
adDialog.Window.Attributes.WindowAnimations = Resource.Style.DialogAnimation_2;
adDialog.Show();
//input.RequestFocus();
SetDialogueTheme(activity, adDialog);
}
catch (Exception ex)
{
throw ex;
}
return adDialog;
}
在activity中的用法:
this.ShowInputDialogue("Title", "", "editetext notes", "Cancel", "Save", async (val) =>
{
try
{
//handle for save
}
catch (Exception ex)
{
}
}, true);