Android: установите поле для редактирования текста в диалоговом окне AlertDialog

Я пытаюсь создать Диалоговое окно оповещения, например Lollipop, все идет хорошо, но я застрял в одном разделе в случае EditText.

Мне нужен EditText с подчеркиванием и полем слева и справа с 20dp. Для подчеркивания я попробовал setBackground() , и он работает нормально.

Но есть проблема, что setBackground() не будет работать API Level ниже 16.

Для setMargin я пробовал

 final EditText input = new EditText(MainActivity.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(30,0,30,0);
    input.setLayoutParams(lp);
    input.setGravity(View.TEXT_ALIGNMENT_GRAVITY);
    input.setBackground(getResources().getDrawable(R.drawable.edit_text_line)); 
    builder.setView(input);

Но редактируйте текст, используя полную родительскую ширину.

Полный код

  AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Message");
    builder.setMessage("Do you want to\n"+""+"exit from app");

    final EditText input = new EditText(MainActivity.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(30,0,30,0);
    input.setLayoutParams(lp);
    input.setGravity(View.TEXT_ALIGNMENT_GRAVITY);
    input.setBackground(getResources().getDrawable(R.drawable.edit_text_line)); //call reequires api 16 and above
    builder.setView(input);

    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "You exit from app " + input.getText().toString(),
                    Toast.LENGTH_LONG).show();

        }
    });

    AlertDialog alert = builder.create();
    alert.show();
    Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.parseColor("#7e7e7e"));
    Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
    pbutton.setTextColor(Color.parseColor("#109c8f"));

Есть ли способ установить background для EditText, который работает ниже API 16, и setMargin слева и справа для EditText.


person Binil Surendran    schedule 19.04.2016    source источник
comment
Одним из способов обхода поля может быть добавление линейного макета и установка левого и правого отступов для этого макета. поместите свой текст редактирования внутри этого linearlayout вместо того, чтобы помещать его непосредственно в диалоговое окно.   -  person Ankit Aggarwal    schedule 19.04.2016
comment
попробуйте использовать ViewGroup.MarginLayoutParams ..!!!   -  person mudit_sen    schedule 19.04.2016
comment
@Binil S смотрите мой ответ ниже.   -  person    schedule 19.04.2016


Ответы (3)


Поля в корневом представлении не будут работать. Попробуйте добавить дополнение к родительскому макету, как сказано в других ответах.
Но вместо того, чтобы создавать макет диалогового окна в Java, я бы посоветовал вам раздуть XML и использовать AppCompatEditText, если вы хотите использовать фон линии
Вот пример кода для вас

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Message");
// Why are you setting message here when you are inflating custom view?
// You need to add another TextView in xml if you want to set message here
// Otherwise the message will not be shown
// builder.setMessage("Do you want to\n"+""+"exit from app");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
final AppCompatEditText input = (AppCompatEditText) view.findViewById(R.id.editText);
builder.setView(view);
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(MainActivity.this, "You exit from app " + input.getText().toString(),
                Toast.LENGTH_LONG).show();

    }
});

AlertDialog alert = builder.create();
alert.show();

Наконец, вы не можете получить кнопки сразу после создания диалога. Вам нужно сделать это в OnShowListener, если вы хотите настроить цвета текста кнопки. Или используйте android.support.v7.app.AlertDialog для новых дизайнов диалогов.

Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
// will be null
// nbutton.setTextColor(Color.parseColor("#7e7e7e"));
Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
// will be null
// pbutton.setTextColor(Color.parseColor("#109c8f"));

dialog_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <android.support.v7.widget.AppCompatEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_margin="16dp"
        app:backgroundTint="@color/colorPrimary"/>

</LinearLayout>
person Rehan    schedule 19.04.2016

Используйте этот код, он работает для меня.

     final EditText input = new EditText(MainActivity.this);
     input.setSingleLine();
     FrameLayout container = new FrameLayout(thisActivity);
     FrameLayout.LayoutParams params = new  FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

     params.topMargin = convertDpToPx(30);
     params.bottomMargin = convertDpToPx(30);

     input.setLayoutParams(params);
     container.addView(input);
person Community    schedule 19.04.2016
comment
При использовании внутри AlertDialog не забудьте добавить контейнер в качестве VIEW для alertDialog:- alertDialog.setView(container); - person Subir Chakraborty; 27.07.2017

Может это поможет

эта работа для меня...

установив RelativeLayout в качестве корня EditText, потому что поля в корневом представлении не будут работать.

public void ShowDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setTitle("App Name");
        alertDialog.setMessage("Message");
        final EditText input = new EditText(getContext());
        input.setHint("Hint Text");
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(36,36,36,36);
        input.setLayoutParams(lp);
        RelativeLayout container = new RelativeLayout(getContext());
        RelativeLayout.LayoutParams rlParams=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        container.setLayoutParams(rlParams);
        container.addView(input);
        //now set view to dialog
        alertDialog.setView(container);
        alertDialog.setPositiveButton("Ohk", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (input.getText().toString().isEmpty()) {
                    input.setText("No Valid");
                    return;
                }
            }
        });
        alertDialog.show();
    }
person Ashvin solanki    schedule 25.03.2019