Search code examples
androidandroid-alertdialogandroid-gridview

How can I create custom alert dialog with grid view in android?


enter image description here

How can I create a Alert Dialog with a GridView as shown in the image above?


Solution

  • Here is a simple implementation: Call this method in your code inside activity.

    private void showAlertDialog() {
            // Prepare grid view
            GridView gridView = new GridView(this);
    
            List<Integer>  mList = new ArrayList<Integer>();
            for (int i = 1; i < 36; i++) {
                mList.add(i);
            }
    
            gridView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, mList));
            gridView.setNumColumns(5);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // do something here
                }
            });
    
            // Set grid view to alertDialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(gridView);
            builder.setTitle("Goto");
            builder.show();
        }