Пример диалогового окна ввода пользовательского запроса Android
В этом руководстве мы улучшим предыдущий примерAlertDialog
, чтобы он мог принимать вводимые пользователем данные, какPromptDialog. Более конкретно, это пользовательский примерAlertDialog
.
Смотрите следующие шаги:
-
Создайте диалоговое окно с подсказкой (файл XML).
-
Прикрепите макет диалогового окна приглашения к
AlertDialog.Builder
. -
Присоедините
AlertDialog.Builder
кAlertDialog
. -
Готово.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
Note
Возможно, вам будет интересно прочитать этотcustom dialog example.
1 файлы макетов Android
Два XML-файла, один для главного экрана, другой для диалогового окна.
Файл: res / layout / main.xml
Файл: res / layout / prompts.xml
2. Деятельность
Прочитайте комментарий и демонстрацию в следующем шаге, он должен быть самоанализом.
Файл: MainActivity.java
package com.example.android; 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; public class MainActivity extends Activity { final Context context = this; private Button button; private EditText result; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // components from main.xml button = (Button) findViewById(R.id.buttonPrompt); result = (EditText) findViewById(R.id.editTextResult); // add button listener button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // get prompts.xml view LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.prompts, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); final EditText userInput = (EditText) promptsView .findViewById(R.id.editTextDialogUserInput); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // get user input and set it to result // edit text result.setText(userInput.getText()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); } }
3. Demo
Запустите его, макет «main.xml
» отображает кнопку и текст редактирования (результат).
Нажмите кнопку, отобразите макет диалогового окна с приглашением «prompts.xml
», введите сообщение «example» и нажмите кнопку «ОК».
Пользовательский ввод «example» перейдет в макет «main.xml
», отредактирует текст (результат) и отобразит его.
Скачать исходный код
Скачать -Android-Prompt-Dialog-Example.zip (16 КБ)