반응형

다이얼로그(dialog)는 전체 화면을 다 채우지 않고 일부 화면만 가리는 윈도우로,  사용자가 예/아니오 같은 선택을 하거나 추가적인 정보 입력을 하기를 기다립니다.  사용자가 응답하기 전까지는 화면에서 사라지지 않고 대기하며 프로그래밍 코드도 잠시 대기상태가 됩니다.(modal event)


여기에서는 Dialog의 서브클래스인 AlertDialog로 만들 수 있는 다이얼로그 예제들을 보여줍니다.

  • 메시지와 예 또는 아니오

  • 리스트

  • 입력창(EditText)

  • 다중 선택 리스트

  • 단일 선택 리스트

  • Custom Layout(로그인창)

  • DialogFragment( Activty에서 호출한 경우 스트링을 반환받는 방법)

  • DialogFragment( Fragment에서 호출한 경우 스트링을 반환받는 방법)


AlertDialog의  구성요소는 다음과 같습니다.

  • Title - 다이얼로그의 제목입니다.

  • Content - 사용자에게 보여줄 내용으로 문자열, 리스트, 커스텀 레이아웃이 가능합니다.

  • Button - 버튼 3개까지 가능합니다.  Positive, Negative, Neutral Button 3가지 타입이 있습니다.

    • Positve -> YES 또는 OK 사용자가 허락

    • Negative -> NO 또는 Cancel 사용자가 불허 혹은 취소

    • Neutral -> Later 결정을 연기



메시지와 예 또는 아니오

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    tools:context=".MainActivity">
 
    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>
</RelativeLayout>
 
cs


MainActivity.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
package com.tistory.webnautes.alertdialog_example;
 
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
    }
 
    void show()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("AlertDialog Title");
        builder.setMessage("AlertDialog Content");
        builder.setPositiveButton("예",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"예를 선택했습니다.",Toast.LENGTH_LONG).show();
                    }
                });
        builder.setNegativeButton("아니오",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"아니오를 선택했습니다.",Toast.LENGTH_LONG).show();
                    }
                });
        builder.show();
    }
}
 
cs





리스트

이후부터는  MainActivity.java에서 show()함수만 바꾸시면 됩니다. Content 영역에 리스트가 보이기 때문에 Content 영역에 문자열을 출력할 수 없습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    void show()
    {
        final List<String> ListItems = new ArrayList<>();
        ListItems.add("사과");
        ListItems.add("배");
        ListItems.add("귤");
        ListItems.add("바나나");
        final CharSequence[] items =  ListItems.toArray(new String[ ListItems.size()]);
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("AlertDialog Title");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int pos) {
                String selectedText = items[pos].toString();
                Toast.makeText(MainActivity.this, selectedText, Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }
cs





입력창(EditText)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    void show()
    {
        final EditText edittext = new EditText(this);
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("AlertDialog Title");
        builder.setMessage("AlertDialog Content");
        builder.setView(edittext);
        builder.setPositiveButton("입력",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),edittext.getText().toString() ,Toast.LENGTH_LONG).show();
                    }
                });
        builder.setNegativeButton("취소",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
 
                    }
                });
        builder.show();
    }
cs





다중 선택 리스트


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
    void show()
    {
        final List<String> ListItems = new ArrayList<>();
        ListItems.add("사과");
        ListItems.add("배");
        ListItems.add("귤");
        ListItems.add("바나나");
        final CharSequence[] items =  ListItems.toArray(new String[ ListItems.size()]);
 
        final List SelectedItems  = new ArrayList();
 
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("AlertDialog Title");
        builder.setMultiChoiceItems(items, null,
            new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which,
                                    boolean isChecked) {
                    if (isChecked) {
                        //사용자가 체크한 경우 리스트에 추가
                        SelectedItems.add(which);
                    } else if (SelectedItems.contains(which)) {
                        //이미 리스트에 들어있던 아이템이면 제거
                        SelectedItems.remove(Integer.valueOf(which));
                    }
                }
            });
        builder.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String msg="";
                        for (int i = 0; i < SelectedItems.size(); i++) {
                            int index = (int) SelectedItems.get(i);
 
                            msg=msg+"\n"+(i+1)+" : " +ListItems.get(index);
                        }
                        Toast.makeText(getApplicationContext(),
                                "Total "+ SelectedItems.size() +" Items Selected.\n"+ msg , Toast.LENGTH_LONG)
                                .show();
                    }
                });
        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
 
                    }
                });
        builder.show();
    }
cs




단일 선택 리스트


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
   void show()
    {
        final List<String> ListItems = new ArrayList<>();
        ListItems.add("사과");
        ListItems.add("배");
        ListItems.add("귤");
        ListItems.add("바나나");
        final CharSequence[] items =  ListItems.toArray(new String[ ListItems.size()]);
 
        final List SelectedItems  = new ArrayList();
        int defaultItem = 0;
        SelectedItems.add(defaultItem);
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("AlertDialog Title");
        builder.setSingleChoiceItems(items, defaultItem,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SelectedItems.clear();
                    SelectedItems.add(which);
                }
            });
        builder.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String msg="";
 
                        if (!SelectedItems.isEmpty()) {
                            int index = (int) SelectedItems.get(0);
                            msg = ListItems.get(index);
                        }
                        Toast.makeText(getApplicationContext(),
                                "Items Selected.\n"+ msg , Toast.LENGTH_LONG)
                                .show();
                    }
                });
        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
 
                    }
                });
        builder.show();
    }
cs








Custom Layout(로그인창)



MainActivity.java


package com.tistory.webnautes.alertdialogtest;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       Button button = (Button)findViewById(R.id.button);
       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               show();
           }
       });
   }

   void show()
   {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
       LayoutInflater inflater = getLayoutInflater();
       View view = inflater.inflate(R.layout.dialog_login, null);
       builder.setView(view);
       final Button submit = (Button) view.findViewById(R.id.buttonSubmit);
       final EditText email = (EditText) view.findViewById(R.id.edittextEmailAddress);
       final EditText password = (EditText) view.findViewById(R.id.edittextPassword);

       final AlertDialog dialog = builder.create();
       submit.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               String strEmail = email.getText().toString();
               String strPassword = password.getText().toString();
               Toast.makeText(getApplicationContext(), strEmail+"/"+strPassword,Toast.LENGTH_LONG).show();

               dialog.dismiss();
           }
       });

       dialog.show();

   }

}




로그인창을 보여줄 레이아웃 파일을 추가합니다.


dialog_login.xml

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
52
53
54
55
56
57
58
59
60
61
62
63
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="16dp" >
 
    <TextView
        android:id="@+id/textviewLogo"
        android:layout_width="221dp"
        android:layout_height="54dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:textSize="40sp"
        android:text="Login" />
 
    <TextView
        android:id="@+id/textviewEmailAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textviewLogo"
        android:text="Email Address"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/edittextEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/textviewEmailAddress">
 
        <requestFocus />
    </EditText>
 
    <TextView
        android:id="@+id/textviewPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/edittextEmailAddress" />
 
    <EditText
        android:id="@+id/edittextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:inputType="textPassword"
        android:layout_below="@+id/textviewPassword" />
 
    <Button
        android:id="@+id/buttonSubmit"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edittextPassword"
        android:layout_marginBottom="20dp"
        android:text="Sign In" />
 
</RelativeLayout>
cs




DialogFragment( Activty에서 호출한 경우 스트링을 반환받는 방법)


1. Fragment에서 인터페이스를 정의합니다.

1
2
3
4
5
    public interface OnCompleteListener{
        void onInputedData(String id, String pass);
    }
 
    private OnCompleteListener mCallback;
cs


2. Activty에서 Fragment에서 정의한 인터페이스를 구현합니다. 이곳에서 Fragment가 전달한 스트링을 받게 됩니다.

1
2
3
4
5
6
public class MainActivity extends AppCompatActivity implements DialogFragmentExample.OnCompleteListener {
 
    @Override
    public void onInputedData(String id, String pass) {
        Toast.makeText(this, id+"/"+pass,Toast.LENGTH_LONG).show();
    }
cs


3. Fragment의 onAttatch 메소드에서 Activty에서 구현한 인터페이스와 연결합니다.

1
2
3
4
5
6
7
8
9
10
11
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
 
        try {
            mCallback = (OnCompleteListener) activity;
        }
        catch (ClassCastException e) {
            Log.d("DialogFragmentExample""Activity doesn't implement the OnCompleteListener interface");
        }
    }
cs


4. Activty에서 버튼이 눌러지는 순간 DialogFragment를 생성하여 화면에 보여줍니다.

1
2
3
4
5
    void show()
    {
        DialogFragment newFragment = new DialogFragmentExample();
        newFragment.show(getFragmentManager(), "dialog"); //"dialog"라는 태그를 갖는 프래그먼트를 보여준다.
    }
cs


5. Fragment에서 Submit 버튼이 눌러지면 다이얼로그를 안보이게 하면서 이메일과 패스워드 스트링을 메인으로 전달해줍니다.

1
2
3
4
5
6
7
8
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strEmail = email.getText().toString();
                String strPassword = password.getText().toString();
                dismiss();
                mCallback.onInputedData(strEmail, strPassword);
            }
        });
cs


로그인창에 이메일주소와 패스워드를 입력후, SIGN IN을 터치하면, 로그인 다이얼로그가 닫힌 후,  Activity에서 전달받은  이메일주소와 패스워드를 출력해줍니다. 



MainActivity.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
package com.tistory.webnautes.alertdialog_example;
 
import android.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
 
public class MainActivity extends AppCompatActivity implements DialogFragmentExample.OnCompleteListener {
 
    @Override
    public void onInputedData(String id, String pass) {
        Toast.makeText(this, id+"/"+pass,Toast.LENGTH_LONG).show();
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
    }
 
    void show()
    {
        DialogFragment newFragment = new DialogFragmentExample();
        newFragment.show(getFragmentManager(), "dialog"); //"dialog"라는 태그를 갖는 프래그먼트를 보여준다.
    }
 
 
}
 
cs


DialogFragmentExample.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
52
53
54
55
56
57
58
package com.tistory.webnautes.alertdialog_example;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
 
public class DialogFragmentExample extends DialogFragment{
 
    public interface OnCompleteListener{
        void onInputedData(String id, String pass);
    }
 
    private OnCompleteListener mCallback;
 
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
 
        try {
            mCallback = (OnCompleteListener) activity;
        }
        catch (ClassCastException e) {
            Log.d("DialogFragmentExample""Activity doesn't implement the OnCompleteListener interface");
        }
    }
 
 
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_login, null);
        builder.setView(view);
        final Button submit = (Button) view.findViewById(R.id.buttonSubmit);
        final EditText email = (EditText) view.findViewById(R.id.edittextEmailAddress);
        final EditText password = (EditText) view.findViewById(R.id.edittextPassword);
 
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strEmail = email.getText().toString();
                String strPassword = password.getText().toString();
                dismiss();
                mCallback.onInputedData(strEmail, strPassword);
            }
        });
 
        return builder.create();
    }
}
 
cs



DialogFragment( Fragment에서 호출한 경우 스트링을 반환받는 방법)


1. MainFragment의 onCreateView 메소드에서 버튼이 클릭시 다이얼로그 프레그먼트가 보여지도록합니다.  이떄 setTargetFragment를 호출하여 현재 프래그먼트에서 결과값을 받을 것이라고 지정해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        View view =  inflater.inflate(R.layout.fragment_main, container, false);
 
        Button button = (Button)view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
 
        return view;
    }
 
    void show()
    {
        DialogFragment newFragment = new DialogFragmentExample();
        newFragment.setTargetFragment(this, DIALOG_REQUEST_CODE );
        newFragment.show(getFragmentManager(), "dialog"); //"dialog"라는 태그를 갖는 프래그먼트를 보여준다.
    }
cs


2.  DialogFragmentExample에서 버튼이 눌러진경우 이메일 주소와 패스워드를 Intent에 넣어서 getTargetFragment().onActivityResult를 호출하며 인자로 넘겨줍니다.  setTargetFragment를 호출했던 MainFragment에서 받게됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strEmail = email.getText().toString();
                String strPassword = password.getText().toString();
 
                Intent data = new Intent();
                data.putExtra ("id", strEmail );
                data.putExtra ("pass", strPassword );
 
                getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data);
 
                dismiss();
            }
        });
cs


3. MainFragment의 onActivityResult 메소드에서 Intent를 받아오게 됩니다. 여기에서는 Toast를 이용하여 화면에 출력해주고 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        if (requestCode == DIALOG_REQUEST_CODE) {
 
            if (resultCode == Activity.RESULT_OK) {
                String id = data.getExtras().getString("id");
                String pass = data.getExtras().getString("pass");
 
                Toast.makeText(getActivity(), id+"/"+pass,Toast.LENGTH_LONG).show();
            }
        }
    }
cs


실행 결과는 이전 예제와 동일합니다. 로그인창에 이메일주소와 패스워드를 입력후, SIGN IN을 터치하면, 로그인 다이얼로그가 닫힌 후,  Activity에서 전달받은  이메일주소와 패스워드를 출력해줍니다. 



activity_main.xml

기존 레이아웃 내용을 fragment_main.xml으로 옮기고 다음 내용으로 변경합니다.

MainActivity에서는 MainFragment를 레이아웃에 추가하여 화면에 보여주게 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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" >
 
    <fragment
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.tistory.webnautes.alertdialog_example.MainFragment"
        tools:layout="@layout/fragment_main" />
 
</FrameLayout>
cs


MainActivity.java

다음 내용만 남기고 전부 MainFragment.java로 옮깁니다. 자신이 하던 작업들을 이젠 MainFragment에서 하게 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.tistory.webnautes.alertdialog_example;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
}
 
cs


fragment_main.xml

MainFragment에서  MainActivity를 대신하여 버튼을 보여줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>
</RelativeLayout>
cs


MainFragment.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
52
53
54
55
56
57
package com.tistory.webnautes.alertdialog_example;
 
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
 
public class MainFragment extends Fragment {
 
    private static final int DIALOG_REQUEST_CODE = 1234;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        View view =  inflater.inflate(R.layout.fragment_main, container, false);
 
        Button button = (Button)view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show();
            }
        });
 
        return view;
    }
 
    void show()
    {
        DialogFragment newFragment = new DialogFragmentExample();
        newFragment.setTargetFragment(this, DIALOG_REQUEST_CODE );
        newFragment.show(getFragmentManager(), "dialog"); //"dialog"라는 태그를 갖는 프래그먼트를 보여준다.
    }
 
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        if (requestCode == DIALOG_REQUEST_CODE) {
 
            if (resultCode == Activity.RESULT_OK) {
                String id = data.getExtras().getString("id");
                String pass = data.getExtras().getString("pass");
 
                Toast.makeText(getActivity(), id+"/"+pass,Toast.LENGTH_LONG).show();
            }
        }
    }
}
 
cs


dialog_login.xml

 앞 예제에서 사용한 것에서 바꾼내용이 없습니다.

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
52
53
54
55
56
57
58
59
60
61
62
63
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:paddingLeft="16dp"
                android:paddingRight="16dp"
                android:paddingTop="16dp" >
 
    <TextView
        android:id="@+id/textviewLogo"
        android:layout_width="221dp"
        android:layout_height="54dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:textSize="40sp"
        android:text="Login" />
 
    <TextView
        android:id="@+id/textviewEmailAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textviewLogo"
        android:text="Email Address"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/edittextEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/textviewEmailAddress">
 
        <requestFocus />
    </EditText>
 
    <TextView
        android:id="@+id/textviewPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_below="@+id/edittextEmailAddress" />
 
    <EditText
        android:id="@+id/edittextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:inputType="textPassword"
        android:layout_below="@+id/textviewPassword" />
 
    <Button
        android:id="@+id/buttonSubmit"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edittextPassword"
        android:layout_marginBottom="20dp"
        android:text="Sign In" />
 
</RelativeLayout>
cs


DialogFragmentExample.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
package com.tistory.webnautes.alertdialog_example;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
 
public class DialogFragmentExample extends DialogFragment{
 
 
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_login, null);
        builder.setView(view);
        final Button submit = (Button) view.findViewById(R.id.buttonSubmit);
        final EditText email = (EditText) view.findViewById(R.id.edittextEmailAddress);
        final EditText password = (EditText) view.findViewById(R.id.edittextPassword);
 
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strEmail = email.getText().toString();
                String strPassword = password.getText().toString();
 
                Intent data = new Intent();
                data.putExtra ("id", strEmail );
                data.putExtra ("pass", strPassword );
 
                getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data);
 
                dismiss();
            }
        });
 
        return builder.create();
    }
}
 
cs


반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts