android – 从Fragment调用DialogFragment

前端之家收集整理的这篇文章主要介绍了android – 从Fragment调用DialogFragment前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从我的Fragment类调用DialogFragment.我有一个 ImageView,并希望在我设置的ImageView的onClickListener中调用我的DialogFragment类.

我在onClick中遇到错误,我设置的代码试图调用DialogFragment.

我在“show”上收到一条错误,说明“DialogFragment类型中的方法show(FragmentManager,String)不适用于参数(FragmentManager,String)”,并且“new Instance”上的错误表明“方法newInstance()未定义MyDialogFragment类型“

这是我的代码

@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类:

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;
    }
}

解决方法

您没有名为newInstance的静态方法.在对话框片段中添加以下内容
public static MyDialogFragment newInstance() {
    MyDialogFragment f = new MyDialogFragment();
    return f;
    }

您可以在文档中找到更多信息和示例

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

猜你在找的Android相关文章