다이얼로그를 프래그먼트로 사용하기 위해서는, 다이얼로그 창도 새로 만들어 줘야한다.

이 방법을 공부하는 과정 역식 정말 신기하고 재미있었다. 안드로이드는 공부할수록 신기한 것 같다.


xml

우선 xml에 사용하고 싶은 다이얼로그의 형태를 정의한다. 그리고 여기서 중요한것은 부모 layout의 width와 height를 wrap_content로 만들어 줘야하는것이다. 이것이 여타 다른 프래그먼트를 만들때 match_parent를 하는것과 차이점이 되겠다. 위의 방법만 유의해서 xml파일을 만들어 주면 된다.


다음은 DialogFragment를 상속받은 class파일을 하나 만들어보자


DialogFragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
public class DialogFragment extends android.support.v4.app.DialogFragment {
 
  ...
 
    public static DialogFragment newInstance(String param1, String param2) {
        DialogFragment fragment = new DialogFragment();
        Bundle arg = new Bundle();
 
        arg.putString("param1", param1);
        arg.putString("param2", param2);
 
        fragment.setArguments(arg);
 
        return fragment;
    }
 
    public DialogFragment(){}
 
 
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        ...
 
    }
 
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {      
 
        ...
 
         AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
 
        builder.setView(view)
            .setPositiveButton("Yes"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Yes 버튼을 눌렀을때 발생하는 이벤트
                    }
        }).setNegativeButton("No"new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                 // No 버튼을 눌렀을때 발생하는 이벤트
            });
 
        return builder.create();
    }
}

cs


DialogFragment의 재미있는 점은 onCreateDialog 메소드가 있다는 점이다. 이를통해 다이얼로그가 띄워졌을때에 대한 화면과 이벤트를 정의하는데, 35행 이하와 같이 builer를 정의해서 그 builder에 PositiveButton과 NegativeButton을 정의해 주는것이다. 이것이 우리가 흔히 알고있는 예/아니오 버튼인 것이다. 위를 통해 우리는 xml파일에 굳이 예/아니오 버튼을 만들 필요가 없으며 간단하게 java파일에서 만들수 있다.


'Programming > Android' 카테고리의 다른 글

가속도 센서를 이용하여 흔들림 감지  (0) 2016.10.12
ListView에 각각 Seekbar 넣기  (0) 2016.09.24
Custom Listview  (0) 2016.09.24
ListFragment  (0) 2016.09.24
ScrollView  (0) 2016.09.15

+ Recent posts