2010-12-14 8 views
0

J'ai mon ListActivity qui lorsque vous appuyez sur un élément, il affiche un dialogue qui demande à l'utilisateur l'utilisateur et le mot de passe. Comment puis-je obtenir la position sélectionnée dans le dialogue?Acess AdapterView from Dialog

Voici comment j'initialiser le ListActivity:

protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 

ListView listView = getListView(); 
listView.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, 
    int position, long id) { 
    showDialog(DIALOG_USER_PASSWORD); 
    } 
}); 
} 

La boîte de dialogue I pop up est un simple AlertDialog avec 2 EditText que je gonfle à partir d'un fichier xml

protected Dialog onCreateDialog(int id) { 
     switch (id) { 
     ... 
     case DIALOG_USER_PASSWORD: 
      LayoutInflater factory = LayoutInflater.from(this); 
         final View dialogView = factory.inflate(R.layout.alert_dialog_text_entry, null); 
         return new AlertDialog.Builder(MyListActivity.this) 
         .setIcon(R.drawable.alert_dialog_icon) 
         .setTitle(R.string.ask_user_password) 
         .setView(dialogView) 
         .setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        String userName = ((EditText) findViewById(R.id.username_edit_alert_dialog)) 
          .getText().toString(); 
        String password = ((EditText) findViewById(R.id.password_edit_alert_dialog)) 
          .getText().toString(); 
        Credentials cred = new CredentialsL1(userName, password); 

        /* HERE IS WHERE i NEED THE SELECTED ITEM 
        mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */ 
        mService.connect(mId, cred); 

        } 
       }) 
       // Cancel button 
       .setNegativeButton(R.string.cancel_text, 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          dialog.cancel(); 
         } 
        }) 
       .create(); 
     } 
     return null; 
    } 

Le seul que je suis venu avec est de créer un nouveau champ "mID" et de le définir lorsque l'utilisateur appuie sur et l'utiliser lorsque l'utilisateur appuie sur OK dans la boîte de dialogue. Une idée plus élégante? Merci

Répondre

1
private int selectedPosition; 
... 
protected void onCreate(Bundle savedInstanceState) { 
.... 
// inside the item listener... 
selectedPosition = position; 
showDialog(DIALOG_USER_PASSWORD); 

/* HERE IS WHERE i NEED THE SELECTED ITEM 
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */ 
// just use selectedPosition var 

idée Pas plus élégante?

Il semble que vous utilisez un ListView normal (et non une case à cocher une) ... donc, il est bien de le faire de cette façon.