详解Android应用中DialogFragment的基本用法

2019-12-10 18:03:29王旭
Android App中建议使用DialogFragment作为对话框的容器,DialogFragment类提供了创建对话框并管理其外观需要的所有控件,本文主要内容便为详解Android应用中DialogFragment的基本用法,而不再需要调用Dialog的方法需要的朋友可以参考下  

DialogFragment的基本用法
1. 创建DialogFragment

public class DialogA extends DialogFragment implements DialogInterface.OnClickListener {

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  builder.setMessage(R.string.dialoga_title)
    .setPositiveButton(R.string.ok, this)
    .setNegativeButton(R.string.cancel, this);

  return builder.create();
 } 

 @Override
 public void onClick(DialogInterface dialog, int id) {
  switch(id) {
   case AlertDialog.BUTTON_NEGATIVE:
    Toast.makeText(getActivity(), "Negative", Toast.LENGTH_SHORT).show();
    break;
   case AlertDialog.BUTTON_POSITIVE:
    Toast.makeText(getActivity(), "Positive", Toast.LENGTH_SHORT).show();
    break;
   default:
    break;
  } 
 } 
}

说明:自定义一个DialogFragment,并重写它的onCreateDialog()方法。
2. 调用该DialogFragment
下面是在FragmentActivity中调用该DialogFragment对话框。

public class DialogTest extends FragmentActivity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  showDialog();
 }

 private void showDialog() {
  FragmentManager fm = getSupportFragmentManager();
  DialogA dialoga = new DialogA();
  dialoga.show(fm, "fragmenta");
 }
}

自定义DialogFragment布局
下面介绍自定义DialogFragment的布局的方法
点击查看:自定义DialogFragment布局的完整代码
1. 设置布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
 xmlns:tools="http://www.easck.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <TextView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="@string/dialoga_intro" />

 <ImageView
  android:id="@+id/image"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/ic_action_video" />

</LinearLayout>