普通的AlertDialog
在横竖屏切换时会被销毁,如果dialog上面有数据,也将丢失。解决方案是使用DialogFragment。
使用dialogFragment
通常需要复写两个方法:
onCreateView(LayoutInflater, ViewGroup, Bundle)
onCreateDialog(Bundle)
如果你想自定义dialog样式,只需要复写onCreateView
,注入一个自定义的view即可,然后通过调用DialogFragment#show()方法即可。
这里我们不需要自定义,只需要托管AlertDialog
即可,所以我们仅仅需要复写onCreateDialog
方法。在这个方法内部我们需要通过AlertDialog.Builder
构建一个dialog并返回,dialog的参数可以通过setArguments
注入。具体代码如下:
package com.taobao.dialogfragmentdemo;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class AlertDialogFragment extends DialogFragment
{
private static final String PARAM_TITLE = "title";
private static final String PARAM_CONTENT = "content";
private static DialogCallback mCallback;
public AlertDialogFragment()
{
}
public static AlertDialogFragment newInstance(String title,String content,DialogCallback callback)
{
AlertDialogFragment instance = new AlertDialogFragment();
Bundle bundle = new Bundle();
bundle.putString(PARAM_TITLE,title);
bundle.putString(PARAM_CONTENT,content);
instance.setArguments(bundle);
mCallback = callback;
return instance;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Bundle params = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(params.getString(PARAM_TITLE));//没有做非空判断,按需添加
builder.setMessage(params.getString(PARAM_CONTENT));
builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
if(mCallback != null)
mCallback.onPostiveClick();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
if(mCallback != null)
mCallback.onNegativeClick();
}
});
return builder.show();
}
public interface DialogCallback
{
public void onPostiveClick();
public void onNegativeClick();
}
}
想使用也很简单:
AlertDialogFragment dialog = AlertDialogFragment.newInstance("标题", "这是fragment托管的alertdialog", new AlertDialogFragment.DialogCallback()
{
@Override
public void onPostiveClick()
{
Toast.makeText(MainActivity.this,"确定",Toast.LENGTH_SHORT).show();
}
@Override
public void onNegativeClick()
{
Toast.makeText(MainActivity.this,"取消",Toast.LENGTH_SHORT).show();
}
});
dialog.show(getSupportFragmentManager(),"dialog");
还可以通过DialogFragment#show
的第二个参数tag来找到对应的dialogFragment:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment prevDialog = getSupportFragmentManager().findFragmentByTag("dialog");
if(prevDialog != null)
{
transaction.remove(prevDialog);
}