본문 바로가기

프로그래밍/안드로이드

[안드로이드] 커스텀 대화상자(Custom Dialog)

※ 저는 안드로이드 프로그래밍 정복(김상형 著, 한빛미디어) 책을 이용해 공부하고 있으며

예제와 코드는 이 책을 통해 공부중임을 밝힙니다.

개인적인 공부를 하면서 정리한 형식이기 때문에 심각한 오류가 있을 수 있습니다. 피드백 주시면 정말 감사하겠습니다.

※ 안드로이드 프로그래밍 정복 820p~831p


1. 커스텀 대화상자


여러 정보를 보여주거나, 입력받으려면 궁극적으로 커스텀 뷰를 사용한다.


AlertDialog.Builder setView (View view)


View로부터 파생된 임의의 뷰를 대화상자 안에 배치할 수 있으며 뷰그룹도 가능하다.


스피너를 한번 달아보려고 했는데 실패했다. ㅠㅠ


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="아래 버튼을 눌러 대화상자를 호출하시오."
/>
<Button
android:id="@+id/call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="대화상자 호출"
/>
</LinearLayout>

기본 레이아웃 1. 레이아웃을 하나 더 만들어줘야 한다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5pt"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="제품"
/>
<EditText
android:id="@+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="수량"
/>
<Spinner
android:id="@+id/genre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numeric="integer"
/>
<CheckBox
android:id="@+id/paymethod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="착불 결제"
/>
</LinearLayout>


public class ExerciseExam extends Activity {


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_excercise_exam);
}

public void mOnClick(View v) {
final LinearLayout linear = (LinearLayout)View.inflate(this, R.layout.find, null);

new AlertDialog.Builder(this)
.setTitle("주문 정보를 입력하시오.")
.setIcon(R.drawable.b)
.setView(linear)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText product = (EditText)linear.findViewById(R.id.product);
EditText number = (EditText)linear.findViewById(R.id.genre);
CheckBox paymethod = (CheckBox)linear.findViewById(R.id.paymethod);
TextView text = (TextView)findViewById(R.id.text);
text.setText("주문 정보 " + product.getText() + " 상품 " +
number.getText() + "개." +
(paymethod.isChecked() ? "착불결제":""));
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
TextView text = (TextView)findViewById(R.id.text);
text.setText("주문을 취소했습니다.");
}
})
.show();
}
}


2. 팝업 윈도우


팝업 윈도는 임의의 뷰를 담을 수 있는 컨테이너이다.

현재 액티비티의 위쪽에 임시적으로 잠시 열리는 창이다.

간단한 메시지나 즉각적인 선택이 필요할 때 원하는 위치에 시녹하게 열 수 있다.


대화상자와 유사하지만 팝업은 Object로부터 직접 파생되는 단독 클래스이며 원하는 곳에 창을 연다.


PopupWindow ()

PopupWindow (View contentView)

PopupWindow (int width, int height)

PopupWindow (View contentView, int width, int height, boolean focusable)

첫 번째 인수 : 팝업 안에 배치할 내용 뷰 (대화상자의 커스텀 뷰에 해당)

두 번째 인수 : 팝업 윈도우의 폭

세 번째 인수 : 팝업 윈도우의 높이

네 번째 인수 : 키보드 입력을 받을 수 있는지 지정


팝업 윈도우의 속성을 정해주는 메서드

void setContentView (View contnetnView)

void setWidth (int width)

void setHeight (int height)

void setFocusable (boolean focusable)


각 메서드는 생성자의 인수와 하나씩 대응된다. 속성 설정 후 다음 메서드로 화면에 "출력"한다.

void showAtLocation (View parent, int gravity, int x, int y)

gravity : NO_GRAVITY 인 경우 Gravity.LEFT | Gravity.TOP 이 지정된다.

void showAsDropDown (View anchor [, int xoff, int yoff])

앵커 뷰를 지정하며 팝업은 앵커 뷰의 왼쪽 아래에 열린다.

xoff, yoff를 추가로 전달하면 offeset만큼 이동한 곳에 열린다.


팝업을 닫을 때 다음 메서드를 호출한다.

void dismiss()

팝업을 닫음

boolean isShowing()

팝업이 화면에 보이는 상태인지 조사


SHOW POPUP을 누르면 150px의 EditText 팝업 윈도우가 나타난다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<Button
android:id="@+id/btnshow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup"
/>
</LinearLayout>

SHOW POPUP 버튼을 구성하는 기본 레이아웃1


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
>
<EditText
android:layout_width="150px"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btnclose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close Popup"
/>
</LinearLayout>

팝업윈도우 창을 구성하는 레이아웃2



public class ExerciseExam extends Activity {

PopupWindow popup;
View popupview;
LinearLayout linear;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_excercise_exam);

linear = (LinearLayout)findViewById(R.id.linear);
popupview = View.inflate(this, R.layout.find, null);
popup = new PopupWindow(popupview,200,150,true);

final Button btnshow = (Button)findViewById(R.id.btnshow);
btnshow.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// 지정한 좌표에 놓기
popup.showAtLocation(linear, Gravity.NO_GRAVITY,100,150);
// 가운데 놓기
//popup.showAtLocation(linear,Gravity.CENTER,0,0);
// 가운데 + 50, 80에 놓기
//popup.showAtLocation(linear,Gravity.CENTER,50,80);
// 화면 벗어나기
//popup.showAtLocation(linear,Gravity.NO_GRAVITY,800,1200);
// 수평 중앙, 수직 바닥
//popup.showAtLocation(linear,Gravity.CENTER_HORIZONTAL|
// Gravity.BOTTOM,0,0);
// 수평 중앙, 수직 바닥 + (50,50)
//popup.showAtLocation(linear,Gravity.CENTER_HORIZONTAL|
// Gravity.BOTTOM,50,50);
// 버튼 아래에 놓기
//popup.setAnimationStyle(-1);
//popup.showAsDropDown(btnshow);
}
});

Button btnclose = (Button)popupview.findViewById(R.id.btnclose);
btnclose.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
popup.dismiss();
}
});
}
}