从Fragment调用DialogFragment

时间:2013-10-08 15:43:26

标签: android android-dialogfragment

我正在尝试从Fragment类中调用DialogFragment。我有一个ImageView,并想在我设置的ImageView的onClickListener中调用我的DialogFragment类。

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

我收到错误" show"说明" DialogFragment类型中的方法show(FragmentManager,String)不适用于参数(FragmentManager,String)"和#34;新实例"上的错误声明"方法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;
    }
}

2 个答案:

答案 0 :(得分:6)

您没有名称为newInstance的静态方法。在对话框片段中添加以下内容

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

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

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

答案 1 :(得分:0)

您还可以在没有newInstance方法的情况下调用 MyDialogFragment

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