2010-06-29 1 views
0

Я использую Alert Dialog as Login. Поэтому после закрытия этого диалога любое значение, назначенное в диалоговом окне show(), теряется. как вернуть это значение? мой код нижехочу вернуть любую ценность после закрытия Alert Dialog

private void accessPinCode() 
{ 
    LayoutInflater factory = LayoutInflater.from(this); 
    final View textEntryView = factory.inflate(R.layout.dialog_login, null); 
    AlertDialog.Builder alert = new AlertDialog.Builder(this);     
    alert.setTitle("Title"); 
    alert.setMessage("Enter Pin :");     
    alert.setView(textEntryView);  

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) {   
      EditText mUserText; 
      mUserText = (EditText) textEntryView.findViewById(R.id.txt_password); 
      //String strPinCode = mUserText.getText().toString(); 
      Log.d(TAG, "Pin Value 1 : " + mUserText.getText().toString());    
      strPIN = mUserText.getText().toString(); 
      Log.d(TAG, "strPIN inside accessPinCode : " + strPIN); 
      fPIN= checkPINCode(); 
      Log.d(TAG, "fPass : " + fPIN); 


      return;     
     } 
    }); 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      return; 
     } 
    }); 

    alert.show(); 
    Log.d(TAG, "strPIN outside Alert Show : " + strPIN); 
} 

На основании моего кода значения strPIN и FPIN теряются. Я хочу использовать эти значения вне функции accessPinCode. как получить?

Фактически, я вызываю эту функцию при событии tabchanged. Если вход в систему проходит, пользователь может получить доступ к другой вкладке. Но все уже работали в событии с измененной вкладкой, прежде чем нажимать кнопку «ОК» AlertDialog. Моя вкладка, как показано ниже

tabHost.setOnTabChangedListener(new OnTabChangeListener() { 

      public void onTabChanged(String tabId) { 
       // TODO Auto-generated method stub 

       if (tabId.equals("index")) 
       { 
        tabHost.setCurrentTab(1); 
        accessPinCode(); 
       } 
       Log.d(TAG, "tabId : "+ tabId);  
      } 
     }); 

Есть ли какой-либо тип диалога для входа? Как решить?

+0

Небольшой совет: используйте 'android.R.string.ok' и' android.R.string.cancel' вместо «Ok» и «Cancel». – Felix

+0

Спасибо. Я буду – soclose

+0

Наконец, вместо вызова метода accessPinCode внутри события Tab OnChanged я помещаю все alertDialog в это событие. Потому что я хочу установить текущую вкладку, если будет проходить вход. Спасибо вам всем. – soclose

ответ

1

Редактировать: В вашей отрицательной/положительной кнопке вы должны вызвать функцию из окружающего класса, установив эти два параметра со значениями, собранными в AlertDialog.

что-то вроде:

private String mStrPin; 
private float mFPin; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

...

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      String strPin = "1234"; 
      float fPin = 1.234f; 
      public void onClick(DialogInterface dialog, int which) { 
       loggedIn(strPin, fPin); 
      } 
    } 

...

} 
private void loggedIn(String strPin, float fPin) { 
    mStrPin = strPin; 
    mFPin = fPin; 
} 
+0

+1 для первой части, -1 для последней части (вы всерьез поощряете это?). – Felix

0

Упрощенный пример:

public interface TextListener { 
    void onPositiveResult(CharSequence text); 
} 

public static AlertDialog getTextDialog(Context ctx, 
     final TextListener listener) { 
    View view = LayoutInflater.from(ctx).inflate(R.layout.dialog, null); 
    final TextView tv = (TextView) view.findViewById(R.id.tv); 
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    builder.setView(view); 
    // 
    builder.setPositiveButton(android.R.string.ok, new OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      listener.onPositiveResult(tv.getText()); 
     } 
    }); 
    builder.setNegativeButton(android.R.string.cancel, null); 
    return builder.create(); 
} 
+0

@ alex, pls перепроверьте мое сообщение. Я снова редактирую. – soclose