본문 바로가기

JAVA/ANDROID

[Android] 다양한 Dialog 종류별 구현 방법 - 펌

[Android]

다양한 Dialog 종류별 구현 방법 - 펌 


참고 URL : 출처: http://mainia.tistory.com/555 [녹두장군 - 상상을 현실로]

>> 원본 그대로를 퍼오고 싶었으나 사정상 약간의 모양에 약간의 변형은 있으나, 모든 자료는 위 출처에 따릅니다.




(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) 프로그레시브(Progress) 다이얼로그 구현

안드로이드에서 프로그레시브바를 구현할수 있다. 이것을 구현하기 위한 클래스는ProgressDialog 를 사용해야 한다. 다이얼로그 창의 중지 ProgressDialog 의 dismiss 를 쓰면된다.


private void DialogProgress(){

       ProgressDialog dialog = ProgressDialog.show(DialogSample.this, "",

                        "잠시만 기다려 주세요 ...", true);

      // 창을 내린다.

      // dialog.dismiss();

}



 


(4) Radio 버튼을 포함한 다중선택 다이얼로그 창

1번 예제와 비슷하게 Radio 버튼이 추가되어있는 다중선택 다이얼로그 창이다. 차이가 있다면 창 타이틀에 setIcon 을 써서 아이콘을 집어넣은것과 선택한

행 번호를 알아와 Toast 로 화면에 문자열을 표시해주는 내용이다. 창을 닫고 싶다면 onclick 함수에 넘어온 DialogInterface 객체로 cancel 함수를 호출해 

닫으면 된다.


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

}


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

    }

 

}