fragment를 이용한 dialog창 띄우기



1. 레이아웃

<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.progdv.fragment_dialog.MainActivity">

<Button
android:id="@+id/btnFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />

</RelativeLayout>




2. 메인 액티비티


package com.progdv.fragment_dialog;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button btnFragment;

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

btnFragment = (Button)findViewById(R.id.btnFragment);
btnFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAlertDialogFragment newDialogFragment =
MyAlertDialogFragment.newInstance("Fragment Dialog 테스트 중...");
newDialogFragment.show(getFragmentManager(), "dialog");
}
});
}

public static class MyAlertDialogFragment extends DialogFragment{

public static MyAlertDialogFragment newInstance(String title){
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//return super.onCreateDialog(savedInstanceState);

String title = getArguments().getString("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.mipmap.ic_launcher)
.setTitle(title)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i("MyLog", "확인 버튼이 눌림");
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i("MyLog", "취소 버튼이 눌림");
}
})
.create();
}
}
}





























Posted by netyhobby
,