Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling DialogFragment from Fragment

I am trying to call a DialogFragment from my Fragment class. I have an ImageView, and would like to call my DialogFragment class in the onClickListener of the ImageView I have set up.

I am getting an error in the onClick with the code I have set up trying to call the DialogFragment.

I am getting an error on "show" stating "The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)" and an error on "new Instance" stating "The method newInstance() is undefined for the type MyDialogFragment"

Here's my code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  Bundle savedInstanceState)
{
    final View v = inflater.inflate(R.layout.image_detail_fragment, 
      container, false);

    mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
    mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            //Here
            MyDialogFragment dialog = MyDialogFragment.newInstance();
            dialog.show(getFragmentManager(), "fragmentDialog");
        }
    });

    return v;
}

DialogFragment class:

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

class MyDialogFragment extends DialogFragment {

    Context mContext;

    public MyDialogFragment() {
        mContext = getActivity();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
        alertDialogBuilder.setTitle("Set Wallpaper?");
        alertDialogBuilder.setMessage("Are you sure?");
        //null should be your on click listener
        alertDialogBuilder.setPositiveButton("OK", null);
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
        });

        return alertDialogBuilder.create();
    }

    public static MyDialogFragment newInstance() {
        MyDialogFragment = new MyDialogFragment;
        return f;
    }
}
like image 268
Jack Avatar asked Oct 08 '13 15:10

Jack


1 Answers

You do not have a static method by the name newInstance. Add the below in your Dialog Fragment

public static MyDialogFragment newInstance() {
    MyDialogFragment f = new MyDialogFragment();
    return f;
    }

You can find more info and an example in the docs

http://developer.android.com/reference/android/app/DialogFragment.html

like image 167
Raghunandan Avatar answered Oct 02 '22 08:10

Raghunandan