Lesson 65. Dialogues. AlertDialog. customization

Lesson 65. Dialogues. AlertDialog. customization


In this lesson:

– we use our View to build a dialogue

In addition to the message or list, we can put our View components into the dialog. For this purpose there is both the main body of the dialogue and the title. To do this, we need to create a View and use the setCustomTitle or setView methods to insert that View into the header or body of the dialog. I will only use setView and work with the body of the dialog. Using the setCustomTitle method and working with the title of the dialog is exactly the same.

We draw an application that will use its View component in the body of the dialog and consider how you can modify the content of this component. We will add and delete TextView in the body of the dialog.

Let’s create a project:

Project name: P0651_AlertDialogCustom
Build Target: Android 2.3.3
Application name: AlertDialogCustom
Package name: en.startandroid.develop.p0651alertdialogcustom
Create Activity: MainActivity

IN strings.xml write down the texts:



    AlertDialogCustom
    Добавить
    Удалить

main.xml – Two-button screen for deleting and adding items to the dialog



    
    

dialog.xml – our future is a caste-body of dialogue.



    
    
    
    

IN tvTime– we will display the current time, and in tvCount – Number of TextViews added.

MainActivity.java:

package ru.startandroid.develop.p0651alertdialogcustom;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

  final int DIALOG = 1;

  int btn;
  LinearLayout view;
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
  TextView tvCount;
  ArrayList textViews;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textViews = new ArrayList(10);
  }

  public void onclick(View v) {
    btn = v.getId();
    showDialog(DIALOG);
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    adb.setTitle("Custom dialog");
    // создаем view из dialog.xml
    view = (LinearLayout) getLayoutInflater()
        .inflate(R.layout.dialog, null);
    // устанавливаем ее, как содержимое тела диалога
    adb.setView(view);
    // находим TexView для отображения кол-ва
    tvCount = (TextView) view.findViewById(R.id.tvCount);
    return adb.create();
  }

  @Override
  protected void onPrepareDialog(int id, Dialog dialog) {
    super.onPrepareDialog(id, dialog);
    if (id == DIALOG) {
      // Находим TextView для отображения времени и показываем текущее
      // время
      TextView tvTime = (TextView) dialog.getWindow().findViewById(
          R.id.tvTime);
      tvTime.setText(sdf.format(new Date(System.currentTimeMillis())));
      // если была нажата кнопка Добавить
      if (btn == R.id.btnAdd) {
        // создаем новое TextView, добавляем в диалог, указываем текст
        TextView tv = new TextView(this);
        view.addView(tv, new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
        tv.setText("TextView " + (textViews.size() + 1));
        // добавляем новое TextView в коллекцию
        textViews.add(tv);
        // иначе
      } else {
        // если коллекция созданных TextView непуста
        if (textViews.size() > 0) {
          // находим в коллекции последний TextView
          TextView tv = textViews.get(textViews.size() - 1);
          // удаляем из диалога
          view.removeView(tv);
          // удаляем из коллекции
          textViews.remove(tv);
        }
      }
      // обновляем счетчик
      tvCount.setText("Кол-во TextView = " + textViews.size());
    }
  }
}

Consider the code. In the method onCreate we follow standard procedures and create a textViews collection to store added TextView.

method onclick – Button handler, stores in btn the button ID and shows a dialog.

In the method of creating dialogue onCreateDialog we specify the title of the dialog and create it view from the dialog.xml layout file and using the setView method, we tell the dialog that we should use our view as a body of dialogue. And now, working with view, We will form a body of dialogue. In the newly created view immediately find tvCount – to display the number of TextViews added.

method onPrepareDialog – here we use the getWindow method to access the View-components of the dialogue, find among them tvTime and show it in time. Next, determine which button was clicked. If the button is added, then we create a TextView and put it in view (Defined in the onCreateDialog method) and added to the textViews collection. This will add TextView to the body of the dialog. If we want to delete TextView, we find in the collection the last added and remove it from the view component and from the textViews collection. Finally, we update the counter of the number of textViews added in the dialog.

Note that I use two different ways to access tvCount and tvTime. I found tvCount immediately after creation view in the onCreateDialog method. And in the case of tvTime, I show you how to find the View component in a dialog without using the object view. Whichever is most convenient for you, use it.

We will save everything and launch the application. Click the Add button

A dialog has appeared. Shows the time, the number of TextViews added, and the TextViews themselves added.

Close the dialog with the Back button, click again to add

Another TextView added.

Close the dialog, click the Delete button.

The last TextView was deleted.

In the next lesson:

– we consider dialog event handlers
– programmatically close and show dialogue




Discuss in the forum [38 replies]

Leave a Comment