2013-07-05 83 views
0

如果在android java編程的異步性質上遇到困難,我該如何在onClick處理程序中拋出異常,或者帶有警告對話框的方法如何返回值?我必須使用變量來傳遞結果嗎?返回一個帶有警告對話框的方法的值

public boolean validAccessCode = false; 

//  public boolean requestAccessCode(Activity mActivity) throws Exception { 
public void requestAccessCode(Activity mActivity) throws Exception { 
    private EditText mPasswordView; 

    mPasswordView = new EditText(mActivity); 
    mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 
    mPasswordView.setTransformationMethod(new PasswordTransformationMethod()); 

    AlertDialog.Builder alert = new AlertDialog.Builder(mActivity); 
    alert.setTitle("Enter access code"); 
    alert.setView(mPasswordView); 

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
     String pw = mPasswordView.getText().toString(); 
     if(pw.equals(accessCode)) 
     { 
     validAccessCode = true; 

     return; 
     } 

     //throw new Exception("Invalid access code"); 
    } 

    alert.show(); 
    }); 

回答

0

U可以使用此處簡單的接口

public interface DialogClickListener { 
    public void onClicked(boolean validAccessCode) 
} 

public void requestAccessCode(Activity mActivity, 
     final DialogClickListener listener) throws Exception { 
private EditText mPasswordView; 

mPasswordView = new EditText(mActivity); 
mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 
mPasswordView.setTransformationMethod(new PasswordTransformationMethod()); 

AlertDialog.Builder alert = new AlertDialog.Builder(mActivity); 
alert.setTitle("Enter access code"); 
alert.setView(mPasswordView); 

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
public void onClick(DialogInterface dialog, int whichButton) { 
    String pw = mPasswordView.getText().toString(); 

    if (listener != null) { 
     listener.onClicked(pw.equals(accessCode)); 
    } 
} 

alert.show(); 

});