0

Я хочу создать AlertDialog и добавить в него два EditText, кнопки Ок и Отмена. Как это можно сделать?

1 ответ 1

1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Напишите текст: "
        android:textAppearance="?"
        androidd:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/input_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
   
    </LinearLayout>
public class MainActivity extends Activity {
    final Context context = this;
    private Button button;
    private TextView final_text;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Инициализируем элементы:
        button = (Button) findViewById(R.id.prompt_button);
        final_text = (TextView) findViewById(R.id.final_text);

        //Добавляем слушателя нажатий по кнопке Button:
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                //Получаем вид с файла prompt.xml, который применим для диалогового 
    окна:
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.prompt, null);

                //Создаем AlertDialog
                AlertDialog.Builder mDialogBuilder = new AlertDialog.Builder(context);

                //Настраиваем prompt.xml для нашего AlertDialog:
                mDialogBuilder.setView(promptsView);

                //Настраиваем отображение поля для ввода текста в открытом диалоге:
                final EditText userInput = (EditText) 
                promptsView.findViewById(R.id.input_text);

                //Настраиваем сообщение в диалоговом окне:
            mDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                    //Вводим текст и отображаем в строке ввода на основном экране:
                        final_text.setText(userInput.getText());
                    }
                })
                .setNegativeButton("Отмена",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        dialog.cancel();
                    }
                });

                 //Создаем AlertDialog:
                 AlertDialog alertDialog = mDialogBuilder.create();

                //и отображаем его:
                alertDialog.show();

            }
        });
    }
}
8
  • И где тут EditText?
    – edcft
    16 июн 2020 в 18:38
  • @edcft обновил ) 16 июн 2020 в 19:03
  • Это конечно хорошо, что вы умеете копировать, но вопервых мне нужно 2 EditText, а во вторых я читал эту статью но не очень понял эти манипуляции с xml файлами. Вы можете как-то объяснить? )
    – edcft
    16 июн 2020 в 19:16
  • а что собственно вам непонятно? напишите разметку с двумя EditText в xml файле и работайте с ними в коде? 16 июн 2020 в 19:35
  • Спасибо, тут разобрался) Скажите, а вы не знаете как сделать так чтобы края этого алерта были закругленными?
    – edcft
    16 июн 2020 в 19:50

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.