Search code examples
androidandroid-fragmentsandroid-gridviewbaseadapterandroid-dialogfragment

Custom gridview in a DialogFragment


I tried to insert a custom gridview into a DialogFragment, and I encountered a problem with setting the adapter to the gridview. After hours of research, I gave up and came here for any ideas on what is the problem with the gridview.setAdapter? Thanks in advance!

The DialogFragment :

public class theDialog extends DialogFragment {

private String[] nums ={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
GridView gridview;
GridAdapter adapter = new GridAdapter(getActivity(),nums);

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    View view=inflater.inflate(R.layout.grid,null);
    gridview = (GridView) getActivity().findViewById(R.id.gridview);
    gridview.setAdapter(adapter); //PROBLEM HERE************

    builder.setView(view);


    Dialog dialog = builder.create();
    return dialog;
}
}

Solution

  • First of all, if you received any errors running your code, you should edit the output of logcat in your question.

    To resolve your problem, you should use view which you have inflated instead of getActivity to find the gridview.

    The fixed DialogFragment :

    public class theDialog extends DialogFragment {
    
    private String[] nums ={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
    GridView gridview;
    GridAdapter adapter = new GridAdapter(getActivity(),nums);
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    
         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
    
        View view=inflater.inflate(R.layout.grid,null);
        // replace getActivity() with view
        gridview = (GridView) view.findViewById(R.id.gridview);
        gridview.setAdapter(adapter); //PROBLEM HERE************
    
        builder.setView(view);
    
    
        Dialog dialog = builder.create();
        return dialog;
    }
    }