web-dev-qa-db-fra.com

Ajoutez une plus grande marge à EditText dans Android AlertDialog

J'ai un EditText dans un AlertDialog. Cela ressemble à ceci.

enter image description here

Voyez où il est écrit tddjdjck et comment il est beaucoup mis en retrait. C'est ce que je veux (j'ai utilisé setPadding avec gauche et droite à 50), mais je veux aussi que la ligne bleue en dessous soit également en retrait. Comment je fais ça?

Le code que j'utilise est ci-dessous:

            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();  

Je vous remercie

36
b85411
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);

Assurez-vous d'ajouter une autre ligne à votre fichier de ressources dimens.xml, telle que

<dimen name="dialog_margin">20dp</dimen>
75
Ashton Engberg

Vous pouvez passer le paramètre d'espacement dans la méthode setView

alert.setView(view ,left_space , top_space , right_space , bottom_space);

Donc, dans votre cas, vous pouvez essayer ceci

alert.setView(input , 50 ,0, 50 , 0);
21
Bhargav Thanki

Voici la fonction d'extension Kotlin pour que le Builder définisse la vue EditText.

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
}

Exemple d'utilisation

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()

Résultat

enter image description here

9
Vadim Akhmerov

Je fais une fonction AlertDialog générale à entrée unique. Le code est explicite.

enter image description here

Utils.Java

public class Utils {

    /**
     * Convert dp to px value.
     * -
     * Source: https://stackoverflow.com/a/6327095/2263329
     */
    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();

}

Exemple d'utilisation:

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() {

                // ...

            }
        });
0