Реализация ввода текста в Alert Dialog
Главная » Реализация ввода текста в Alert Dialog

В этом несложном уроке мы научимся, как снабдить Alert Dialog нашего приложения функционалом ввода текста и передачи его на activity. Такую функцию можно часто видеть во многих Android приложениях. 

Проект будет состоять из следующих частей:

- создания для диалога собственного интерфейса с помощью отдельного layout файла;

- привязки этого файла к объекту AlertDialog.Builder приложения;

- привязка AlertDialog.Builder к AlertDialog.

Создаем новый проект, выбираем Blank Activity. Переходим к созданию интерфейса программы. Откроем файл activity_main.xml и добавим сюда элементы Button и TextView:

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

 <Button
 android:id="@+id/prompt_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Показать Prompt Dialog" />

 <TextView
 android:id="@+id/final_text"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </TextView>

</LinearLayout>

Кнопка будет использоваться для вызова диалога Alert Dialog, а поле ввода TextView - для отображения введенного в диалоге текста.

Теперь нужно создать отдельный layout файл, в котором задать вид будущего диалогового окна. В папке layout создаем файл под названием prompt.xml и добавляем в него следующий код:

<?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="?android:attr/textAppearanceLarge" />

 <EditText
 android:id="@+id/input_text"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 <requestFocus />
 </EditText>

</LinearLayout>

Теперь остается только немного по кодить в файле MainActivity.java. Открываем файл и добавляем туда следующее:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

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

 }
 });
 }
}

В принципе, ничего сложного и нового, все это мы уже неоднократно видели. Запускаем приложение и смотрим, что вышло:

Ввод текста в диалоге Результат в основном активити

Все нормально, работает :).

Категория: Уроки программирования | Просмотров: 1569 | Добавил: Oleg | Теги: Android приложение, передача данных, Текст, Alert Dialog | Рейтинг: 5.0/2
Всего комментариев: 0
avatar