ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 안드로이드 개발 다이얼로그 종류별로 구현하는 방법
    Dung--[안드로이드 개발] 2023. 4. 12. 17:11

    안드로이드 개발 다이얼로그 종류별로 구현하는 방법

     

    1. 여러 개의 멀티선택 옵션들로 표현하여 주기

    다중선택을 하기위한 다이얼로그 창을 띄웁니다. 리스트에 제목과 radio button이 있습니다. AlertDialog Builder 클래스로 구현을 하며 리스트중 특정행을 클릭하였을 때에 이벤트는 setSingleChoiceitems에 등록합니다. OK 버튼클릭 이벤트는 setPositiveButton, Cancel 버튼 클릭 이벤트는 setNegativeButton에 등록한후 기능을 구현하시면 됩니다.


    private void DialogSelectOption() {
    final String items[] = { "item1", "item2", "item3" };
    AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
    ab.setTitle("Title");
    ab.setSingleChoiceItems(items, 0,
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // 각 리스트를 선택하였을 때에
    }
    }).setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // OK 버튼 클릭시 , 여기서 선택한 값을 메인 Activity 로 넘겨버리면 된다
    }
    }).setNegativeButton("Cancel",
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // Cancel 버튼 클릭시
    }
    });
    ab.show();
    }

     

    2. html 로 구현시킨 text 넣어주기

    다이얼로그 창을 띄울 때에 공지나 경고성 창이라고 한다면 내용이 들어갈것입니다. 이 내용을 HTML 태그를 적용하여 넣을 수가 있습니다. 색깔은 제대로 바뀌는것 같지만 <strong>,<b>등의 글자에 대한 bold 처리를 한것이나 안한것이나 똑같이 보여서 제대로 표현이 되는지 조금더 테스트를 해봐야 할것입니다.


    private void DialogHtmlView() {
    AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
    ab.setMessage(Html.fromHtml("<strong><font color=\"#ff0000\"> " + "Html 표현여부 "
    + "</font></strong><br>HTML 이 제대로 표현되는지 봅니다."));
    ab.setPositiveButton("ok", null);
    ab.show();
    }

     

    3. 프로그레시브 다이얼로그의 구현 방법

    안드로이드에서는 프로그레시브바를 구현시킬 수 있습니다. 구현하기 위해서는 클래스는 progressDialog를 활용하여야 합니다. 다이얼로그 창의 중지는 progressDialog의 dismiss를 사용하면 됩니다.


    private void DialogProgress(){
           ProgressDialog dialog = ProgressDialog.show(DialogSample.this, "",
                    "잠시 기다려주시겠습니까 ...", true);
          // 창을 내립니다.
          // dialog.dismiss();
    }

     

     

    4. Radio 버튼을 포함하여 다중선택 다이얼로그 창

    1번의 예시와 비슷한 Radio 버튼이 추가되어진 다중선택 다이얼로그 화면입니다.

    다른부분이 있다면 창의 타이틀에 seticon을 사용하여 아이콘을 집어넣은것 그리고 선택한 행 번호를 알아와 Toast로 화면에 문자열을 표시하여주는 내용입니다.

    창을 닫고 싶으시다면 onclick 함수에 넘어온 Dialoginterface 객체로 cancle함수를 불러와 닫으시면 됩니다.


    private void DialogRadio(){
    final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
            AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
            alt_bld.setIcon(R.drawable.icon);
            alt_bld.setTitle("Select a Phone Model");
            alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show();
                    // dialog.cancel();
                }
            });
            AlertDialog alert = alt_bld.create();
            alert.show();
    }

     

     

    5. 선택에 따른 로직구현을 위한 디이얼로그 창의 구현 방법

    예를 들자면 Yes/No 둘중 하나를 선택함으로서 특정 기능을 구현하여주고자 할때 쓸만한 예제입니다. 샘플에서는 Yes/No를 구분하여서 코드를 구현할 수 있도록 나뉘어져 있습니다. 흔히 볼수 있는 대표적인 다이얼로그 화면입니다.


    private void DialogSimple(){
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setMessage("창을 닫으시겠습니까 ?").setCancelable(
    false).setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    // Action for 'Yes' Button
    }
    }).setNegativeButton("No",
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    // Action for 'NO' Button
    dialog.cancel();
    }
    });
    AlertDialog alert = alt_bld.create();
    // Title for AlertDialog
    alert.setTitle("Title");
    // Icon for AlertDialog
    alert.setIcon(R.drawable.icon);
    alert.show();
    }


     

    6. Time Picker 시간선택 컨트롤을 다이얼로그에 구현하기

    Time Picker 컨트롤을 다이얼로그 창에다 구현한 예시입니다. 다이얼로그에 구현되어 있는 Time Picker에서 선택 되어진 값을 부모 화면에서 받아 그 값을 Toast 로 보여줍니다.


    private void DialogTimePicker(){
    TimePickerDialog.OnTimeSetListener mTimeSetListener = 
    new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    Toast.makeText(DialogSample.this,
    "Time is=" + hourOfDay + ":" + minute, Toast.LENGTH_SHORT)
    .show();
    }
    };
    TimePickerDialog alert = new TimePickerDialog(this, 
    mTimeSetListener, 0, 0, false);
    alert.show();
    }

     

    7. Date Picker 날짜 선택 컨트롤을 다이얼로그에 구현하기

    Date picker 컨트롤을 다이얼로그 창에다 구현한 예시 화면입니다. 또한 다이얼로그에 구현되어 있는 Date Picker에 선택한 값을 부모 화면에서 받을 그 값을 Toast 로 보여줍니다. 창을 띄우시기 전에 현재 날짜 정보를 넘겨준후 Date Picker에서 그것을 받아 표시하여 줍니다.


    private void DialogDatePicker(){
        Calendar c = Calendar.getInstance();
        int cyear = c.get(Calendar.YEAR);
        int cmonth = c.get(Calendar.MONTH);
        int cday = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog.OnDateSetListener mDateSetListener = 
    new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
         String date_selected = String.valueOf(monthOfYear+1)+
          " /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
         Toast.makeText(DialogSample.this, 
    "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
    }
         };
         DatePickerDialog alert = new DatePickerDialog(this,  mDateSetListener,  
         cyear, cmonth, cday);
         alert.show();
    }
     

    8 전체적인 소스


    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import android.app.AlertDialog;
    import android.app.DatePickerDialog;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.app.TimePickerDialog;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.text.Html;
    import android.util.Log;
    import android.view.View;
    import android.widget.DatePicker;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TimePicker;
    import android.widget.Toast;

    public class DialogSample extends ListActivity {

    private String[] mMenuText;
    private String[] mMenuSummary;

    private String keyName = "name";
    private String keyDesc = "desc";
    private String TAG;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TAG = getClass().getName();

    int length = 7;
    mMenuText = new String[length];
    mMenuSummary = new String[length];

    mMenuText[0] = "다중선택 새창";
    mMenuSummary[0] = "다중선택을 할수 있는 Alert 예시 구현입니다.";
    mMenuText[1] = "HTML 적용 새창";
    mMenuSummary[1] = "Text 에 HTML 을 적용하는 Alert 예시 구현입니다.";
    mMenuText[2] = "프로그레시브바 새창";
    mMenuSummary[2] = "진행중을 나타내는 프로그레시브바 Alert 예시구현입니다.";
    mMenuText[3] = "Radio 버튼 새창";
    mMenuSummary[3] = "Radio 버튼이 들어간 새창 이며 선택하면 창이 닫힙니다. ";
    mMenuText[4] = "Simple Dialog";
    mMenuSummary[4] = "선택에 따른 로직구현을 위한 다이얼로그 창 구현";
    mMenuText[5] = "Time Picker";
    mMenuSummary[5] = "Time Picker 시간선택 컨트롤을 다이얼로그에 구현";
    mMenuText[6] = "Date Picker";
    mMenuSummary[6] = "Date Picker 날짜선택 컨트롤을 다이얼로그에 구현";

    setListAdapter(new SimpleAdapter(this, getListValues(), 
    android.R.layout.simple_list_item_2, new String[] {
    keyName, keyDesc }, new int[] { android.R.id.text1, android.R.id.text2 }));
    }

    private List<Map<String, String>> getListValues() {
    List<Map<String, String>> values = new ArrayList<Map<String, String>>();
    int length = mMenuText.length;
    for (int i = 0; i < length; i++) {
    Map<String, String> v = new HashMap<String, String>();
    v.put(keyName, mMenuText[i]);
    v.put(keyDesc, mMenuSummary[i]);
    values.add(v);
    }
    return values;
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Log.d(TAG, "id : " + id + ", position : " + position);
    switch (position) {
    case 0:
    // 다중선택 옵션창
    this.DialogSelectOption();
    break;
    case 1:
    // HTML 구현
    this.DialogHtmlView();
    break;
    case 2:
    // 프로그레시브바 구현
    this.DialogProgress();
    break;
    case 3:
    // Radio 버튼이 추가된 다중선택 창
    this.DialogRadio();
    break;
    case 4:
    // 가장 일반적인 Yes/NO기능구현 Dialog
    this.DialogSimple();
    break;
    case 5:
    this.DialogTimePicker();
    break;
    case 6:
    // 날짜 선택 Dialog 구현
    this.DialogDatePicker();
    break;
    default:
    break;
    }
    }

    private void DialogSelectOption() {
    final String items[] = { "item1", "item2", "item3" };
    AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
    ab.setTitle("Title");
    ab.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // 각 리스트를 선택했을때
    }
    }).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // OK 버튼 클릭시 , 여기서 선택한 값을 메인 Activity 로 넘기면 된다.
    }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // Cancel 버튼 클릭시
    }
    });
    ab.show();
    }

    private void DialogHtmlView() {
    AlertDialog.Builder ab = new AlertDialog.Builder(DialogSample.this);
    ab.setMessage(Html.fromHtml("<strong><font color=\"#ff0000\"> " + "Html 표현여부 "
    + "</font></strong><br>HTML 이 제대로 표현되는지 본다."));
    ab.setPositiveButton("ok", null);
    ab.show();
    }

    private void DialogProgress() {
    ProgressDialog dialog = 
    ProgressDialog.show(DialogSample.this, "", "잠시만 기다려 주세요 ...", true);

    // 창을 내린다.
    // dialog.dismiss();
    }

    private void DialogRadio() {
    final CharSequence[] PhoneModels = { "iPhone", "Nokia", "Android" };
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setIcon(R.drawable.icon);
    alt_bld.setTitle("Select a Phone Model");
    alt_bld.setSingleChoiceItems(PhoneModels, -1, 
    new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int item) {
    Toast.makeText(getApplicationContext(), "Phone Model = " 
    + PhoneModels[item], Toast.LENGTH_SHORT)
    .show();
    dialog.cancel();
    }
    });
    AlertDialog alert = alt_bld.create();
    alert.show();
    }

    private void DialogSimple() {
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setMessage("Do you want to close this window ?").setCancelable(false)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    // Action for 'Yes' Button
    }
    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    // Action for 'NO' Button
    dialog.cancel();
    }
    });
    AlertDialog alert = alt_bld.create();
    // Title for AlertDialog
    alert.setTitle("Title");
    // Icon for AlertDialog
    alert.setIcon(R.drawable.icon);
    alert.show();
    }

    private void DialogTimePicker() {
    TimePickerDialog.OnTimeSetListener mTimeSetListener = 
    new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    Toast.makeText(DialogSample.this, "Time is=" + hourOfDay + ":" 
    + minute, Toast.LENGTH_SHORT).show();
    }
    };
    TimePickerDialog alert = 
    new TimePickerDialog(this, mTimeSetListener, 0, 0, false);
    alert.show();
    }

    private void DialogDatePicker() {
    Calendar c = Calendar.getInstance();
    int cyear = c.get(Calendar.YEAR);
    int cmonth = c.get(Calendar.MONTH);
    int cday = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog.OnDateSetListener mDateSetListener = 
    new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    String date_selected = String.valueOf(monthOfYear + 1) + " /" 
    + String.valueOf(dayOfMonth) + " /"
    + String.valueOf(year);
    Toast.makeText(DialogSample.this, "Selected Date is =" 
    + date_selected, Toast.LENGTH_SHORT).show();
    }
    };
    DatePickerDialog alert = 
    new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
    alert.show();
    }

    댓글

Designed by Tistory.