从我的片段调用对话框片段

时间:2015-03-04 18:45:45

标签: java android android-fragments

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

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

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

类型,未定义newInstance()

这是我的代码:

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

        setListenerOnWeight(root);
        button(root);


        return root;
    }

    public void setListenerOnWeight(View v) {
        EditText Weight = (EditText) v.findViewById(R.id.Weight_up);
        Weight.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                weight_frag dialog = new weight_frag.newInstance();
                dialog.show(getFragmentManager(), "fragmentDialog");

            }


        });
    }

表示我的DialogFragment类:

package com.the.healthescort;


import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class weight_frag extends DialogFragment {

    Context mContext;

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

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

    @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();
    }




}

1 个答案:

答案 0 :(得分:0)

我认为你应该替换

import android.app.Fragment;

import android.support.v4.app.Fragment;

在你的"我的片段"类

你还应该在你的dialogfragment类中提供一个名为newInstance的方法,如下所示:

   public static weight_frag newInstance(){
    weight_frag frag = new weight_frag();
    return frag;
    }

请遵循java命名约定,使用大写字母作为起始字母(WeightFragment)