tpbapp
tpbapp

Reputation: 2506

How to show a Fragment in a Dialog?

I have created a fragment with some text and an image:

public class ContentFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  

        View view = inflater.inflate(R.layout.fragment_content, container, false);

        return view;  

    }

}

Is there any way to get it to show in a dialog?

For example:

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

builder.setTitle("Showing a fragment in a dialog");

// Load fragment as dialog content somehow

AlertDialog alert = builder.create();

alert.show();

Upvotes: 0

Views: 101

Answers (2)

Lowkey
Lowkey

Reputation: 836

AlertDialog is not supposed to host a fragment.

A workaround you can use is to replace dialog UI, which can be achieved by:

dialog.setContentView(R.layout.fragment_content)

This will just change the dialog view, if you want to bind events or data to the controls inside your fragment, you need to do it after setContentView

Upvotes: 1

NickF
NickF

Reputation: 5737

Every dialog has setView method which you can create programmatically or inflate, see this example
You should also consider to use a DialogFragment

Upvotes: 1

Related Questions