在onItemClick之后关闭AlertDialog - 自定义ListViewDialog

时间:2014-07-16 07:57:05

标签: android android-dialog

我正在尝试在用户单击位于对话框中的ListView中的项目后关闭对话框。这是调用打开对话框的listDialog方法:

public void listDialog() {
LayoutInflater shoppingListInflater = LayoutInflater.from(this);

//volley request to get listview data
getListsRequest();

final View allListsView = shoppingListInflater.inflate(R.layout.list_picker_dialog, null);

listsPickerView = (ListView) allListsView.findViewById(R.id.shopping_lists_all);

shoppingLists = new ArrayList<ShoppingList>();

allListsAdapter = new ShoppingListsAdapter(this, shoppingLists);

listsPickerView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

        shopping_list_id = ((TextView) view.findViewById(R.id.list_id)).getText().toString();
        JSONObject listItemData = new JSONObject();

        try {
            listItemData.put("inventory_item_id", inventory_item_id);
            listItemData.put("shopping_list_id", shopping_list_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

// a volley network call to an api
        createListItemRequest(listItemData);

//where I want to close the dialog - after the network call. Not working currently
        alertD.cancel();
    }
});

listsPickerView.setAdapter(allListsAdapter);

AlertDialog.Builder listsDialog = new AlertDialog.Builder(this);

listsDialog.setView(allListsView);

listsDialog.setCancelable(false)
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

    AlertDialog alertD = listsDialog.create();

    alertD.show();

}

除对话框取消外,一切正常。因为alertD不在ItemClickListener中,所以我无法引用它。如何在网络呼叫之后关闭此对话框 - 在上面引用?

1 个答案:

答案 0 :(得分:1)

与JavaScript相比,Java变量的范围从定义它们的地方开始。所以在定义之前你不能引用alertD。

只需将调用移至alertD定义后面的listsPickerView.setOnItemClickListener,另外将alertD声明为final:

 final AlertDialog alertD = listsDialog.create();

 listsPickerView.setOnItemClickListener(....);

 alertD.show();