从Fragment中调用DialogFragment

6
我想从我的Fragment类中调用DialogFragment。我有一个ImageView,并且希望在我设置的ImageView的onClickListener中调用我的DialogFragment类。
在尝试调用DialogFragment的onClick中,我遇到了错误。
我在“show”上得到一个错误,指出“DialogFragment中的show(FragmentManager,String)方法不适用于参数(FragmentManager,String)”,并在“newInstance”上得到一个错误,指出“MyDialogFragment”的“newInstance()”方法未定义。
以下是我的代码:
@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;
    }
}

1
我看不到你的静态方法 MyDialogFragment.newInstance()。 - Aleksandr
2个回答

6

我在"MyDialogFragment"上遇到了错误,提示"MyDialogFragment无法解析为变量"和"f无法解析为变量"。我已经更新了我的代码,你可以看看它的样子。 - Jack
2
请注意!public static MyDialogFragment newInstance() { MyDialogFragment f = new MyDialogFragment(); return f; } - Aleksandr
从Fragment本身传递数据到DialogFragment(例如在多选视图中保留选择)而不是将数据传递到Activity,然后在DialogFragment中检索该数据,这种做法是否可行? - user1841702

0

你也可以直接调用MyDialogFragment,而不需要使用newInstance方法,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接