반응형



어플을 종료하거나 특정작업을 수행할 때 사용자알림의 목적으로 다이얼 로그(Dialog)가 사용되는 경우가 있죠.


이번 예제소스는 안드로이드 어플에서 많이 사용되어지는 AlertDialog

사용자가 원하는 모양으로 커스터마이즈(Customize)하는 예제 입니다.


이 예제는 회원명단 추가를 위해 이름과 국적을 입력할 수 있는 Dialog를 만들어 보여주는 예제입니다.


'이름'은 EditText를 이용하여 입력받습니다.

'국적'은 RadioButton을 통해 선택하도록 하였습니다.


버튼을 누르면 멤버정보를 입력할 수 있는 Dialog를 보여주고

입력을 완료하면

메인화면의 TextView에 추가된 멤버들의 정보를 보여줍니다.


우선 어떻게 동작하는 지 먼저 살펴보고 소스코드를 소개하겠습니다.


실행화면


Button 1개와 TextView1개로 된 메인화면과 버튼을 클릭했을 때 보여지는 커스텀 다이얼로그(Custom AlertDialog) 

 


'이름'으로 'Hong' 입력하고 Korea Radio 버튼선택 후 '완료'버튼 클릭

 


다시 'Add Member...'버튼 클릭하여 'Robin' 입력완료

  


계속해서 '기욤 패드리' 입력 완료

 


입력을 취소할 때

 




먼저 메인 레이아웃 파일입니다.
Button 1개와 TextView 1개로 이루어진 간단한 레이아웃입니다.

 

 activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

    

    <Button 

        android:id="@+id/btn_add_member"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Add Member Dialog show"

        android:onClick="mOnClick"/>

    

    <TextView 

        android:id="@+id/text"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:textSize="18sp"

        android:textStyle="bold"

        android:padding="5dp"/>   


</LinearLayout>

 



다음으로 Custom Dialog에 보여질
'이름' 입력 EditText와 '국적'입력 RadioButton 들의 배치를 설계한
레이아웃 파일 입니다.

res폴더>>layout폴더>>dialog_addmember.xml 로 만들었습니다.

 

 dialog_addmember.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="250dp"

    android:layout_height="wrap_content"

    android:orientation="vertical"

    android:padding="5dp" >

    

    <LinearLayout 

        android:layout_width="match_parent"

        android:layout_height="30dp"

        android:orientation="horizontal"

        android:weightSum="5">

        

        <TextView 

            android:layout_width="0dp"

            android:layout_height="match_parent"

            android:layout_weight="1.5"

            android:text="NAME"

            android:textSize="12sp"

            android:gravity="center"/>

        

        <EditText

            android:id="@+id/dialog_edit" 

            android:layout_width="0dp"

            android:layout_height="match_parent"

            android:layout_weight="3.5"

            android:hint="input name"

            android:textSize="12sp"

            android:gravity="center"/>

        

    </LinearLayout>

    

    <LinearLayout 

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:weightSum="5">

        

        <TextView 

            android:layout_width="0dp"

            android:layout_height="match_parent"

            android:layout_weight="1.5"

            android:text="NATION"

            android:textSize="12sp"

            android:gravity="center"/>

        

        <RadioGroup 

        android:id="@+id/dialog_rg"

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:layout_weight="3.5"

        android:orientation="vertical">            

        

        <RadioButton 

            android:id="@+id/dialog_rb_korea"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="KOREA"

            android:textSize="12sp"/>

        

        <RadioButton 

            android:id="@+id/dialog_rb_canada"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="CANADA"

            android:textSize="12sp"/>

        

        <RadioButton 

            android:id="@+id/dialog_rb_france"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="FRANCE"

            android:textSize="12sp"/>

        

        <RadioButton 

            android:id="@+id/dialog_rb_mexico"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="MEXICO"

            android:textSize="12sp"/>

        

        <RadioButton 

            android:id="@+id/dialog_rb_poland"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="POLAND"

            android:textSize="12sp"/>

        

        <RadioButton 

            android:id="@+id/dialog_rb_saudi"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="SAUDI ARABIA"

            android:textSize="12sp"/>

        

    </RadioGroup>

        

    </LinearLayout>


</LinearLayout>  

 



다음은 소스파일입니다.
주석이 많아서 그렇지 사실 작업내용은 얼마 안됩니다.
빽빽한 코드의 모습에 미리 한숨쉬지 않길 바랍니다.

 MainActivity.java


public class MainActivity extends Activity {

TextView text;//Dialog를 통해 입력된 멤버의 정보를 출력하는 TextView 참조변수

String str="";//빈 문자열 String 객체


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

text= (TextView)findViewById(R.id.text);

}

//onClick 속성이 부여된 View를 클릭했을 때 자동으로 호출되는 메소드

public void mOnClick(View v){

switch( v.getId() ){

case R.id.btn_add_member://멤버 추가(데이터 추가)

//Dialog에서 보여줄 입력화면 View 객체 생성 작업

//Layout xml 리소스 파일을 View 객체로 부불려 주는(inflate) LayoutInflater 객체 생성

LayoutInflater inflater=getLayoutInflater();

//res폴더>>layout폴더>>dialog_addmember.xml 레이아웃 리소스 파일로 View 객체 생성

//Dialog의 listener에서 사용하기 위해 final로 참조변수 선언

final View dialogView= inflater.inflate(R.layout.dialog_addmember, null);

//멤버의 세부내역 입력 Dialog 생성 및 보이기

AlertDialog.Builder buider= new AlertDialog.Builder(this); //AlertDialog.Builder 객체 생성 

buider.setTitle("Member Information"); //Dialog 제목

buider.setIcon(android.R.drawable.ic_menu_add); //제목옆의 아이콘 이미지(원하는 이미지 설정)

buider.setView(dialogView); //위에서 inflater가 만든 dialogView 객체 세팅 (Customize)

buider.setPositiveButton("Complite", new OnClickListener() {

//Dialog에 "Complite"라는 타이틀의 버튼을 설정

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

//멤버 정보의 입력을 완료하고 TextView에 추가 하도록 하는 작업 수행

//dialogView 객체 안에서 NAME을 입력받는 EditText 객체 찾아오기(주의: dialaogView에서 find 해야함)

EditText edit_name= (EditText)dialogView.findViewById(R.id.dialog_edit);

//dialogView 객체 안에서 NATION을 입력받는 RadioGroup 객체 찾아오기

RadioGroup rg= (RadioGroup)dialogView.findViewById(R.id.dialog_rg);

//EditText에 입력된 이름 얻어오기

String name= edit_name.getText().toString();

//선택된 RadioButton의 ID를 RadioGroup에게 얻어오기

int checkedId= rg.getCheckedRadioButtonId();

//Check 된 RadioButton의 ID로 라디오버튼 객체 찾아오기

RadioButton rb= (RadioButton)rg.findViewById(checkedId);

String nation= rb.getText().toString();//RadionButton의 Text 얻어오기

//TextView의 이전 Text에 새로 입력된 멤버의 데이터를 추가하기

//TextView로 멤버리스트를 보여주는 것은 바람직하지 않음.다음 포스트에서 ListView로 처리합니다.

String s= name+"   "+nation+"\n";

str+= s;

text.setText(str);

//TextView에 추가작업을 완료 하였기에 '완료'했다는 메세지를 Toast로 출력

Toast.makeText(MainActivity.this, "새로운 멤버를 추가했습니다", Toast.LENGTH_SHORT).show();

}

});

buider.setNegativeButton("Cancel", new OnClickListener() {

//Dialog에 "Cancel"이라는 타이틀의 버튼을 설정

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

//멤버 정보의 입력을 취소하고 Dialog를 종료하는 작업

//취소하였기에 특별한 작업은 없고 '취소'했다는 메세지만 Toast로 출력

Toast.makeText(MainActivity.this, "멤버 추가를 취소합니다", Toast.LENGTH_SHORT).show();

}

});

//설정한 값으로 AlertDialog 객체 생성

AlertDialog dialog=buider.create();

//Dialog의 바깥쪽을 터치했을 때 Dialog를 없앨지 설정

dialog.setCanceledOnTouchOutside(false);//없어지지 않도록 설정

//Dialog 보이기

dialog.show();

break;

}//switch

}//mOnClickMethod

}


 

 

반응형

+ Recent posts