Please Enable JavaScript!
Gon[ Enable JavaScript ]

반응형

안드로이드(Android) AlertDialog.Builder 상속받아 화면 디자인 가능한 AlertDialog 만들기

 

환경 : Eclipse Mars, Android 4.2.2

 

AlertDialog 클래스는 안드로이드에서 제공하는 기본 다이얼로그 입니다. 그런데 팝업창을 디자인 하고 싶다면 어떻게 할까요? 보통 Dialog 클래스를 상속받아 사용자가 직접 만든 레이아웃으로 화면을 만듭니다. 이것처럼 AlertDialog 도 제목 부분과 메시지 부분의 분리해서 사용자가 직접 디자인 할수 있습니다. inflate 를 사용해서 View 위젯을 만든후 AlertDialog 에서 지원하는 setCustomTitle(), setView() 함수를 이용하는 것이죠.

 

AlertDialog 를 자주 사용한다면 Builder 클래스를 따로 만들어서 사용하시는 것이 좋겠죠. 이렇게 AlertDialog.Builder 를 상속받아서 클래스를 만들게 되면 제목과 내용부분을 자신이 원하는 형태로 디자인 할수 있습니다. 아래 소스는 레이아웃 xml 만 있으면 View.inflate() 함수를 이용해서 View 객체를 만들수 있습니다. 이렇게 만든 View 들을 setCustomTitle(), setView() 의 인수로 넘깁니다. setCustomTitle() 은 제목에 해당하는 영역이며 setView() 는 본문입니다.

 

View customTitle = View.inflate(mContext, R.layout.alert_dlg_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);

View customMessage = View.inflate(mContext, R.layout.alert_dlg_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);

 

AlertDialog.Builder 클래스를 상속받아서 만든 Builder 클래스의 전체 소스 입니다. 레이아웃에 제목값과 내용을 가져오기 위해서는 setTitle(), setMessage() Override 하시면 됩니다.

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAlertDialogBuilder extends AlertDialog.Builder {

    private final Context mContext;
    private TextView mTitle;
    private ImageView mIcon;
    private TextView mMessage;

    public CustomAlertDialogBuilder(Context context) {
        super(context);
        mContext = context; 

        View customTitle = View.inflate(mContext, R.layout.alert_dlg_title, null);
        mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
        mIcon = (ImageView) customTitle.findViewById(R.id.icon);
        setCustomTitle(customTitle);

        View customMessage = View.inflate(mContext, R.layout.alert_dlg_message, null);
        mMessage = (TextView) customMessage.findViewById(R.id.message);
        setView(customMessage);
    }

    @Override
    public CustomAlertDialogBuilder setTitle(int textResId) {
        mTitle.setText(textResId);
        return this;
    }
    @Override
    public CustomAlertDialogBuilder setTitle(CharSequence text) {
        mTitle.setText(text);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setMessage(int textResId) {
        mMessage.setText(textResId);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setMessage(CharSequence text) {
        mMessage.setText(text);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setIcon(int drawableResId) {
        mIcon.setImageResource(drawableResId);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setIcon(Drawable icon) {
        mIcon.setImageDrawable(icon);
        return this;
    }
}

 

▼ 아래 XML 소스는 본문에 해당하는 화면 레이아웃 입니다. 내용이 많을수 있으므로 ScrollView 위젯을 넣어서 스크롤이 되도록 만들었습니다.

 

alert_dlg_message.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/scrollView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="2dip"
            android:paddingBottom="12dip"
            android:paddingLeft="14dip"
            android:paddingRight="10dip">
            
    <TextView android:id="@+id/message"
                style="?android:attr/textAppearanceMedium"
                android:textColor="#888888"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="5dip" />
</ScrollView>

 

▼ 아래 XML 은 제목에 해당하는 화면 레이아웃 입니다. 제목부분을 다른 형태로 꾸미고 싶다면 이 부분을 고치시면 되겠죠.

 

alert_dlg_title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    
    <LinearLayout
            android:id="@+id/title_template"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:layout_marginTop="6dip"
            android:layout_marginBottom="9dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip">

            <ImageView android:id="@+id/icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:paddingTop="6dip"
                android:paddingRight="10dip"
                android:src="@drawable/ic_launcher" />
            <TextView android:id="@+id/alertTitle"
                android:singleLine="true"
                android:ellipsize="end"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
</LinearLayout>

 

▼ 아래 소스는 AlertDialog.Builder 클래스를 상속받아서 만든 Builder 클래스를 사용하고 있는 메인 Activity 전체 소스 입니다. new CustomAlertDialogBuilder AlertDialog.Builder 를 생성하고 있습니다. 나머지 부분은 달라진 것이 없습니다.

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AlertDialogActivity extends Activity implements
		OnClickListener {

	final Context context = this;
	private Button button;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alert_dialog);

		button = (Button) findViewById(R.id.btn_alert);

		// 클릭 이벤트 
		button.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_alert:
			AlertDialog.Builder alertDialogBuilder = new CustomAlertDialogBuilder(context);
			
			// 제목셋팅
			alertDialogBuilder.setTitle("프로그램 안내");
			
			// AlertDialog 셋팅
			alertDialogBuilder
					.setMessage("공지사항 내용표현")
					.setCancelable(false)
					.setPositiveButton("종료",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialog, int id) {
									// 프로그램을 종료한다
									AlertDialogActivity.this.finish();
								}
							})
					.setNegativeButton("취소",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialog, int id) {
									// 다이얼로그를 취소한다
									dialog.cancel();
								}
							});

			// 다이얼로그 생성
			AlertDialog alertDialog = alertDialogBuilder.create();

			// 다이얼로그 보여주기 
			alertDialog.show();
			break;

		default:
			break;
		}
	}
}
반응형
Posted by 녹두장군1
,