Call DialogFragment from a fragment

I am trying to call DialogFragment from my Fragment class. I have an ImageView, and I would like to name my DialogFragment class in onClickListener from the ImageView that I created.

I get an error in onClick with the code that I configured while trying to call DialogFragment.

I get an error "show": "Show method (FragmentManager, String) in type DialogFragment is not applicable for arguments (FragmentManager, String)" and an error in "new instance" indicating "Method newInstance () is undefined for type MyDialogFragment"

Here is 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; } } 
+6
source share
2 answers

You do not have a static method called newInstance . Add below to your dialog fragment

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

More information and an example can be found in the docs.

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

+6
source

And you can also call MyDialogFragment without a newInstance method, for example

 DialogFragment newFragment = new MyDialogFragment(this); newFragment.show(getFragmentManager(), "date_picker"); 
0
source

Source: https://habr.com/ru/post/955505/


All Articles