【问题标题】:Yes or No confirmation in Android Preferences [duplicate]Android首选项中是或否确认[重复]
【发布时间】:2014-03-28 22:32:48
【问题描述】:

我需要在“设置”中实现“重置”选项。单击设置时,应打开一个简单的对话框,要求确认。

我查看了DialogPreference,但似乎无法在任何地方找到好的解决方案或教程。有人可以帮我吗?我是初学者,想法甚至代码都会很有帮助,谢谢。

【问题讨论】:

    标签: android android-preferences dialog-preference


    【解决方案1】:

    我使用了一个简单的解决方案,它确实有效,但我不知道这是否是最好的方法。

    YesNo 类:

    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"
            />
    

    【讨论】:

      【解决方案2】:

      检查此链接。使用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);
          }
      }
      

      【讨论】:

      • 我知道如何使用AlertDialog,我不明白的是如何实现DialogPreference子类。我应该重写哪些函数?
      • 查看我的更新答案
      • 是的,我做了类似的事情,谢谢!
      猜你喜欢
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      相关资源
      最近更新 更多