从对话框访问适配器视图

时间:2010-12-14 10:39:26

标签: android alertdialog listactivity android-adapterview

我有我的ListActivity,当你点击一个项目时,它弹出一个Dialog,询问用户的用户名和密码。如何从对话框中获取所选位置?

以下是我初始化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);
  }
 });
}

我弹出的对话框是一个简单的AlertDialog,带有2个EditText,我从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;
    }

我唯一想到的是创建一个新字段“mId”并在用户点击并在用户点击对话框中的OK时使用它时设置它。还有更优雅的想法吗? 感谢

1 个答案:

答案 0 :(得分: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
  
    

更优雅的想法?

  

您似乎使用普通的ListView(不是复选框)...所以,这样做很好。