我需要在设置中实现“重置”选项。当单击该设置时,应打开一个简单的对话框询问确认。
我已经查看了DialogPreference,但似乎找不到一个好的解决方案或教程。请有经验的人给我帮忙。我是初学者,任何想法甚至代码都将非常有帮助,谢谢。
我已经查看了DialogPreference,但似乎找不到一个好的解决方案或教程。请有经验的人给我帮忙。我是初学者,任何想法甚至代码都将非常有帮助,谢谢。
请检查此链接,使用AlertDialog.Builder
,非常容易实现。
http://developer.android.com/guide/topics/ui/dialogs.html
或者使用DialogPreference
...
将此添加到首选项 xml 中
<com.examples.app.CustomDialogPreference
android:title="Title"
android:dialogMessage="Message"
android:positiveButtonText="Yes"
android:negativeButtonText="No"/>
在你的代码中,创建一个自定义对话框。这可能有些奇怪,但你必须这样做。
public class CustomDialogPreference extends DialogPreference{
public CustomDialogPreference(Context oContext, AttributeSet attrs){
super(oContext, attrs);
}
}
package com.me.myapp;
public class YesNo extends DialogPreference
{
public YesNo(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
protected void onClick()
{
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setTitle("Reset application?");
dialog.setMessage("This action will delete all your data. Are you sure you want to continue?");
dialog.setCancelable(true);
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//reset database
Toast.makeText(getContext(), "Application reset!", Toast.LENGTH_SHORT).show();
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.cancel();
}
});
AlertDialog al = dialog.create();
al.show();
}
}
在XML文件中的偏好设置:
<com.me.myapp.YesNo
android:title="Reset application"
android:summary="Delete all data"
/>