Android GridView项目单击“警报”对话框

时间:2015-05-17 18:05:56

标签: android gridview dialog alert

我有AlertDialog GridView来选择颜色,现在我想在点击项目时关闭AlertDialog。我该怎么办?

private void Alert_Colori() {
    final AlertDialog.Builder customDialog = new AlertDialog.Builder(this);        
    LayoutInflater inflater = this.getLayoutInflater();
    View view = inflater.inflate(R.layout.color_picker, null);

    GridView gridViewColors = (GridView) view.findViewById(R.id.gridViewColors);
    gridViewColors.setAdapter(new ColorPickerAdapter(this));

    gridViewColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         //here close the dialog
        }
    });

    customDialog.setView(view);
    customDialog.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int arg1) {
            dialog.dismiss();

        }
    });
    customDialog.setView(view);
    customDialog.show();
}

3 个答案:

答案 0 :(得分:0)

首先添加

final Dialog dialog = customDialog .create();
行后

final AlertDialog.Builder customDialog = new AlertDialog.Builder(this);  

然后在您的代码中添加此内容

dialog.dismiss();

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     //here close the dialog
}

即,ItemClickListener的代码如下

gridViewColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            dialog.dismiss();
        }
});

另外,请记住customDialog.show();更改为dialog.show()

答案 1 :(得分:0)

执行此操作 - customDialog.dismiss();

尝试更改

final AlertDialog.Builder customDialog = new AlertDialog.Builder(this);

 final AlertDialog customDialog = new AlertDialog.Builder(this);  
在您的原始代码中

-

private void Alert_Colori() {
 final AlertDialog customDialog = new AlertDialog.Builder(this);        
 LayoutInflater inflater = this.getLayoutInflater();
 View view = inflater.inflate(R.layout.color_picker, null);

GridView gridViewColors = (GridView) view.findViewById(R.id.gridViewColors);
gridViewColors.setAdapter(new ColorPickerAdapter(this));

gridViewColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     //here close the dialog
     customDialog.dismiss(); 
   }
});

customDialog.setView(view);
customDialog.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int arg1) {
        dialog.dismiss();

    }
});
customDialog.setView(view);
customDialog.show();
}

答案 2 :(得分:0)

如此处所述:https://stackoverflow.com/a/23372134使用AlertDialog

获取create的实例