Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use material dialog in fragment

I'm using material-dialogs library https://github.com/afollestad/material-dialogs
my problem is I can't use the lib in the fragment

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        layout=inflater.inflate(R.layout.fragment_option, null);
        new MaterialDialog.Builder(this) //the problem is this line
           .title("test")
           .content("test")
           .show();
        return layout;
    }

I have tried below methods but they failed

 new MaterialDialog.Builder(getActivity())
 new MaterialDialog.Builder(this.getActivity())
 new MaterialDialog.Builder(MainActivity.this) //MainActivity is the parent activity

Thank you for any help you can provide

like image 953
Emad Avatar asked Jan 31 '26 02:01

Emad


1 Answers

You can't get context in onCreateView() method of Fragment because fragment in not added to Activity.

The only way is to get Context in onAttach(Activity activity) (or later methods of Fragments lifecicle) method of Fragment.

So you could show dialog this way:

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Context ctx=this.getActivity();
new MaterialDialog.Builder(ctx)
       .title("test")
       .content("test")
       .show();
}

UPD_0:

Make sure you're using version 23.0.1 of Google libs (AppCompat, Support Library, etc.) in your own app. (link)

UPD_1:

Since onAttach(Activity activity) is deprecated, use onAttach(Context context)

like image 194
mohax Avatar answered Feb 01 '26 15:02

mohax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!