What
一种更加灵活的Dialog
Why
谷歌推荐,但是有时不能够满足需求,比如定制边距,突出关闭按钮,当然你也可以使用Dialog形式的Activity
目标效果:
How
1. 继承DialogFragment并重写onCreateDialog方法
public abstract class AbstractCustomDialogFragment extends DialogFragment{
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog alertDialog = new Dialog(getContext());
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View customView = onCreateDialogView();
alertDialog.setContentView(customView);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
WindowManager.LayoutParams windowParams = alertDialog.getWindow().getAttributes();
windowParams.width = (int) (getResources().getDisplayMetrics().widthPixels -
getResources().getDisplayMetrics().density * 20);
alertDialog.getWindow().setAttributes(windowParams);
return alertDialog;
}
//提供接口用来获取Dialog样式
public abstract View onCreateDialogView();
}
2.继承AbstractCustomDialogFragment,重写onCreateDialogView方法
public class MyDialogFragment extends AbstractCustomDialogFragment {
private View mView;
@Override
public View onCreateDialogView() {
mView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_my_dialog, null);
mView.findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
return mView;
}
}
3.在调用的地方调用
MyDialogFragment dialogFragment = new MyDialogFragment();
dialogFragment.show(getSupportFragmentManager(), "FirstDialog");
4.对应的fragment_my_dialog.xml
文件
<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="wrap_content"
android:background="@android:color/transparent"
tools:context="study.ung.maitamaresearch.dialogs.MyDialogFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/margin_10dp"
android:background="@color/transparent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/hello_blank_fragment" />
</RelativeLayout>
<ImageView
android:id="@+id/imageView"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="@drawable/close" />
</RelativeLayout>