我目前正在使用AlertDialog在我的应用程序中创建一个简单的对话框。我使用的代码如下所示:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle(DialogTitle);
builder.setItems(R.array.options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
reset();
break;
case 1:
exit();
break;
default:
break;
}
}
});
builder.show();
我已经读过,最好的选择可能是创建一个扩展DialogFragment的类,然后使用我的DialogFragment代替当前的实现。
任何人都可以确认这是最佳解决方案,建议更好的方法,并可能给我一个例子吗?
谢谢。
答案 0 :(得分:1)
public class ListDialogFragment extends DialogFragment
{
// Use this instance of the interface to deliver action events
private listDialogListener mListener;
private String title;
private int items;
/**
* Create a new instance of EndGameDialogFragment, String dialogTitle
* and ing dialogListItems as an argument.
*/
static ListDialogFragment newInstance(String dialogTitle, int dialogListItems)
{
ListDialogFragment frag = new ListDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("title", dialogTitle);
args.putInt("items", dialogListItems);
frag.setArguments(args);
return frag;
}
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
public interface listDialogListener
{
public void onDialogClick(DialogFragment dialog, int which);
}
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try
{
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (listDialogListener) activity;
}
catch (ClassCastException e)
{
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
title = getArguments().getString("title"); //retrive the titleString
items = getArguments().getInt("items"); //retrive array of items for the list (from strings.xml)
//build the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch(which)
{
case 0:
mListener.onDialogClick(ListDialogFragment.this, which);
break;
case 1:
mListener.onDialogClick(ListDialogFragment.this, which);
break;
default:
break;
}
}
});
return builder.create();
}
}
答案 1 :(得分:0)
您可以覆盖活动的onConfigurationChanged(Configuration newConfig)
方法以识别方向更改,并恢复AlertDialog
(如果已打开)。为此,您需要在清单android:configChanges="orientation
的活动定义中使用以下标记。可以找到一个很好的介绍here。