简体   繁体   中英

How To set a Dialog Box on clicking a Gridview item?

I am new to android. I want to have a dialog box with positive and negative buttons when i click on a gridview item. Right now when i click on an item, it populates another activity with the information of the item that i clicked on.

For example, using putExtra and getExtras , populating the activity works great. Now all i want is that instead of the action being performed on gridView click, i want the action being performed on the ok button of the Alertdialog box.

How should i set the gridview.setOnCLickListener so that it pops up an alertDialog Box when an item is clicked??

         gridView.setOnItemClickListener(new 
         AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int 
             position, long id) {
            gridView.setClickable(true);
        item= (Hotel) parent.getItemAtPosition(position);

                                    String names = item.getName();
                                    Intent i=new 
             Intent(HotelList.this,UserViewActivity.class);
                                    i.putExtra("names",names);
                                    startActivity(i);

        }

    });

First, remove gridView.setClickable(true). It's simply not necessary. Second, You can create the Dialog in your code:

AlertDialog ad = new AlertDialog.Builder(this).setContentView(R.layout.activity_dialog).show();

Try out the following code:

 @Override
    public void onItemClick(AdapterView<?> parent, View view, int 
         position, long id) {

        item= (Hotel) parent.getItemAtPosition(position);

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(false);
        dialog.setTitle("Your Title");
        dialog.setMessage("Your Message" );
        dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            String names = item.getName();
            Intent i= new Intent(HotelList.this,UserViewActivity.class);
            i.putExtra("names",names);
            startActivity(i);
            alert.cancel();
          }
        })
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            alert.cancel();
            }
        });

        final AlertDialog alert = dialog.create();
        alert.show();
    }

});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM