【问题标题】:How to reshow an alert dialog after it's dimissed如何在错过后显示警报对话框
【发布时间】:2011-11-18 17:54:53
【问题描述】:

大约一个星期以来,我一直在用头撞桌子。希望有人可以提供帮助。

这就是我想要做的。

  • 显示登录警告对话框。 -- 最好我喜欢股票的外观,所以 alertdialog.builder 对我有用。我尝试过制作自定义对话框,但我似乎无法让按钮看起来正确。

  • 如果密码正确,则启动活动,但如果在取消或正确之前不重新显示对话框。

这听起来很直接,但我就是无法理解它。我的代码看起来很垃圾 我知道我一直在剪切和粘贴东西。

我最初是在 oncreate 和每个错误密码之后调用 getpasswd 方法。 Unfortuantley 改变方向时我的窗口泄露了。所以我尝试了这个 oncreatedialog 的东西,我不再泄漏,但我无法在旋转之间保留我的 edittext 文本框,即使输入不正确,按下“ok”按钮后我也无法重新显示对话框。任何指针将不胜感激。

谢谢。

package com.mstamp.dreamhostpal; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class GetLoginPassword extends Activity { public static String MY_PREFS = "Settings"; private static final String TAG = "MyActivity"; String value; String crypto; String text; boolean setup; String cleartxt; boolean cancel_pushed; private static final int ALERT_DIALOG1 = 1; Dialog dialog; //final EditText input = new EditText(this); boolean dismissed = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setup_password); loadPreferences(); // showDialog(ALERT_DIALOG1); // getPasswd(); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(ALERT_DIALOG1); //getPasswd(); } protected void onPause() { super.onPause(); //dialog.dismiss(); if (cancel_pushed == false) { //EXIT(); } } private void EXIT() { this.finish(); } public void loadPreferences() { int mode = Activity.MODE_PRIVATE; SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, mode); crypto = mySharedPreferences.getString("cryptedAPIKey", null); setup = mySharedPreferences.getBoolean("setup", false); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case ALERT_DIALOG1: dialog= getPasswd(); break; default: dialog = null; } return dialog; } private Dialog getPasswd() { Dialog dialog; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setCancelable(false); alert.setTitle("Login"); // Set an EditText view to get user input final EditText input = new EditText(this); //final EditText editTextPasswordFirst= (EditText)d.findViewById(R.id.EditTextPasswordFirst); input.setHint("Password"); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { value = input.getText().toString(); // Do something with value! if (value != null && value.trim().length() == 0) { Context context = getApplicationContext(); CharSequence text = "Please enter a password."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); getPasswd(); } else if (value.trim().length() < 5 && value.trim().length() > 0) { Context context = getApplicationContext(); CharSequence text = "The password must be 5 characters or greater."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); //getPasswd(); dismissed = true; } else { try { if (setup) { cleartxt = CryptoHelper.decrypt(value, crypto); Intent MainCommandsList = new Intent(); MainCommandsList.setClassName("com.mstamp.dreamhostpal", "com.mstamp.dreamhostpal.MainCommandsList"); MainCommandsList.putExtra("cleartxtAPIKey", cleartxt); MainCommandsList.putExtra("cleartxtpassword", value); startActivity(MainCommandsList); } if (!setup) { cleartxt = CryptoHelper.decrypt(value, crypto); Intent GetCommandsMakeDatabase = new Intent(); GetCommandsMakeDatabase.setClassName("com.mstamp.dreamhostpal", "com.mstamp.dreamhostpal.GetCommandsMakeDatabase"); GetCommandsMakeDatabase.putExtra("cleartxtAPIKey", cleartxt); GetCommandsMakeDatabase.putExtra("cleartxtpassword", value); startActivity(GetCommandsMakeDatabase); EXIT(); } } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); Context context = getApplicationContext(); CharSequence text = "That password was incorrect."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); getPasswd(); } } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. cancel_pushed = true; EXIT(); } }); dialog = alert.create(); return dialog; //alert.show(); }

【问题讨论】:

    标签: android android-alertdialog orientation-changes


    【解决方案1】:

    你可以这样做:

        private void launchLoginDialog() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Enter your username and password");
    
    LayoutInflater factory = LayoutInflater.from(this);
    View varianceDialogView = factory.inflate(R.layout.loginDialog,null);
    
    alert.setView(loginDialogView);
    alert.setTitle(R.string.loginDialogTitle);
    
    alert.setPositiveButton("login", new DialogInterface.OnClickListener() {
    
        public void onClick(DialogInterface dialog, int whichButton) {
        if (IsLogincheckOk == false){
            launchLoginDialog();
        }
        else{
            doWhatYouWant();
        }
        }
    });
    
    alert.show();
       }
    

    【讨论】:

    • 有没有办法可以构建对话框而不使用布局来膨胀?如果我膨胀一个布局,我会失去 android 的 alertdialog 的股票外观。但据我了解,我需要 EditText 有一个 id,以便在方向更改时自动保存输入的文本。
    【解决方案2】:

    根据你的密码对话框,你可能需要重新加载 Activity。

    因此,如果密码错误,您只需创建一个意图,然后再次调用该活动。

    在哪里检查密码是否正确,如果不正确,试试这个:

    Intent i = new Intent(this, GetLoginPassword.class);
    
    startActivity(i);
    

    但是,我没有尝试使用同一活动中的意图调用活动,因此您必须尝试一下,但我认为它可能会起作用。

    我实现处理密码的方式有点复杂。

    我在 PasswordPrompt Activity 的 onStart 方法中调用了我自己的自定义 Dialog 类,如下所示:

    myPWRslt = new OnReadyListener();
    objPwPrompt = new PasswordDialog(SecurityPrompt.this, myPWRslt);
    objPwPrompt.show();
    

    在我的自定义 PasswordDialog Dialog 类中,我声明了一个已定义的自定义接口,用于处理输入密码的结果。我设置了一个全局变量,用于检查是否输入了成功的密码。

    protected interface ReadyListener {
      abstract void ready(int iResultCode);
    

    然后,输入密码后,我在 PasswordPrompt Activity 类中定义了 ReadyListener 接口。如果输入了错误的密码,将再次显示该对话框。如果按下取消,则应用程序退出。

    private class OnReadyListener implements PasswordDialog.ReadyListener {
        @Override
        public void ready(int iResultCd) {
          try {
            switch (iResultCd) {
            case PasswordDialog.RESULT_LOGIN_SUCCESS_CODE:
              PasswordPrompt.this.setBlPasswordOK(true);
              Intent i = new Intent(PasswordPrompt.this, myMainActivity.class);
              startActivity(i);
    
              PasswordPrompt.this.finish();
              break;
    
            case PasswordDialog.RESULT_LOGIN_INCORRECT_CODE:
              PasswordPrompt.this.setBlPasswordOK(false);
              objPWClass.showDialog(iResultCd);
              break;
    
            case PasswordDialog.RESULT_EXCEEDED_ATTEMPTS_CODE:
              PasswordPrompt.this.setBlPasswordOK(false);
              objPWClass.showDialog(iResultCd);
              break;
    
            case PasswordDialog.RESULT_LOGIN_CANCELLED_CODE:
              PasswordPrompt.this.setBlPasswordOK(false);
              // exit application
              System.gc();
              PasswordPrompt.this.finish();
              break;
    
            default:
              break;
            }// end switch
          }// end try
          catch (Exception error) {
            //handle the error
          }// end try/catch (Exception error)
        }// end public void result(boolean success)
    
      }// end OnReadyListener
    

    这是我的 PasswordDialog 布局的 XML:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:id="@+id/LinearLayout01" 
                  android:layout_width="fill_parent" 
                  android:layout_height="fill_parent"
                  android:orientation="vertical" >
    
    
      <EditText 
            android:id="@+id/txtPwEntry" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:text=""
            android:inputType="textPassword"
            android:selectAllOnFocus="true"
            android:hint="Enter your Password"
            android:nextFocusDown="@+id/btnPwSubmit" 
            android:maxLength="25" >
      </EditText>
    
      <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:stretchColumns="*"
            android:background="#000000"
            >
            <TableRow android:background="#000000" android:layout_margin="2dp">
               <LinearLayout
                  android:id="@+id/myWidget248"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal"
                  android:layout_marginBottom="5dp"
                  >
               <Button 
                   android:id="@+id/btnPwSubmit"
                   android:layout_width="fill_parent" 
                   android:layout_height="wrap_content"
                   android:layout_weight="0.5"
                   android:textStyle="bold"
                   android:textSize="14sp"
                   android:text="Submit" >
               </Button>
               <Button 
                   android:id="@+id/btnPwCancel"
                   android:layout_width="fill_parent" 
                   android:layout_height="wrap_content"
                   android:layout_weight="0.5" 
                   android:textSize="14sp"
                   android:text="Cancel" >
               </Button>
             </LinearLayout>
            </TableRow>
      </TableLayout>
    </LinearLayout>
    

    【讨论】:

    • 这让我明白了这个.. 未捕获的处理程序:线程主因未捕获的异常而退出 E/AndroidRuntime(152):java.lang.IllegalStateException:指定的孩子已经有一个父母。您必须首先在孩子的父母上调用 removeView()。但谢谢你的想法。
    • 虽然如果我添加dismissDialog(ALERT_DIALOG1);到 onPause() 它工作。谢谢。
    • 我从 PasswordDialog Dialog 类的布局中添加了 XML。如果不将其设置在自定义 Dialog 类的 onCreate 中,我不知道如何进行布局。
    • 谢谢您,先生。我去看看。
    • 没问题。很高兴我能帮上忙,在获得了本网站其他用户的大量帮助之后。
    猜你喜欢
    • 2019-04-21
    • 2023-03-25
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2023-03-13
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多