当前位置: 首页 > 知识库问答 >
问题:

在OnClickListener中实现DialogFraank接口

田兴旺
2023-03-14

我需要构建一个对话框,它将用户输入从对话框返回到活动。该对话框需要在OnClickListener中调用,当列表视图中的元素被单击时调用该对话框。
对话片段的返回值(用户的输入)应该直接在活动中的OnClickListener中可用。

我试图通过坚持官方文件来实现这一点:http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

我需要下面这样的东西,但它行不通,因为我不知道如何让匿名OnClickListener实现CustomNumberPicker类的接口
据我所知,为了将数据从DialogFragment返回活动,实现接口是必要的。

主要活动:

public class MainAcitivity extends ActionBarActivity {
    [...]

    // ArrayAdapter of the Listview
    private class ListViewArrayAdapter extends ArrayAdapter<Exercise> {
        public ListViewArrayAdapter(Context context, ArrayList<Exercise> exercises) {
            super(context, 0, exercises);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            [...]

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_workoutdetail, parent, false);
            }

            TextView tvSets = (TextView) convertView.findViewById(R.id.tvWorkoutExerciseSets);
            tvSets.setText(sets.toString());

            // OnClickListener for every element in the ListView
            tvSets.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // This is where the Dialog should be called and
                    // the user input from the Dialog should be returned
                    DialogFragment numberpicker = new CustomNumberPicker();
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
                }

                // Here I would like to implement the interface of CustomNumberPicker
                // in order to get the user input entered in the Dialog
            });

            return convertView;
        }
    }
}

CustomNumberPicker(与文档中的基本相同):

public class CustomNumberPicker extends DialogFragment {

    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Sets")
            .setPositiveButton("set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Return stuff here to the activity?
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

共有3个答案

巢海
2023-03-14

它是这样做的:在显示DiaogFraank的活动中,使用所需的名称值对设置DialogFraank的参数。还要确保活动实现了DialogInterface。OnClickListener在覆盖的onClick中从上述名称值对中获取值

public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener {

        private static SettingsFragment settingsFragment;
        private Button btnSettings;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);

            btnSettings = (Button) findViewById(R.id.btnSettings);

            btnSettings.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    settingsFragment = new SettingsFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("myKey", null);
                    settingsFragment.setArguments(bundle);
                    //Use the commented out line below if you want the click listener to return to a fragment instead of an activity
                    //assuming that this class in a fragment and not an activity
                    //rotateSettingsFragment.setTargetFragment(getActivity().getSupportFragmentManager().findFragmentByTag("TagForThisFragment"), 0);
                    settingsFragment.setTargetFragment(settingsFragment, 0);
                    settingsFragment.setCancelable(true);
                    settingsFragment.show(getSupportFragmentManager(), "SettingsFragment");

                }
            });

        }

        @Override
        public void onClick(DialogInterface dialog, int which) {

            if(getResources().getResourceEntryName(which).equals("btnSettingFragmentClose")) {

                String myValue = settingsFragment.getArguments().getString("myKey");
                dialog.dismiss();

            }

        }

    }

在DialogFragment中声明一个DialogInterface。OnClickListener并将其强制转换为onAttach中的活动。如果需要将数据发回活动;设置buddle参数,然后调用onClickListener。onClick(单击)

公共类设置片段扩展了DialogFragment{

private View rootView;
private Button btnSettingFragmentClose;
private DialogInterface.OnClickListener onClickListener;

public SettingsFragment() {}

/* Uncomment this and comment out on onAttach when you want to return to a fragment instead of an activity.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    onClickListener = (DialogInterface.OnClickListener) getTargetFragment();

}
*/

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_settings, container, false);
    btnSettingFragmentClose = (Button) rootView.findViewById(R.id.btnSettingFragmentClose);

    btnSettingFragmentClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getArguments().putString("myKey", "Hello World!");
            onClickListener.onClick(getDialog(), v.getId());

        }
    });

    return rootView;

}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {

        onClickListener = (DialogInterface.OnClickListener) activity;

    }
    catch (ClassCastException e) {

        throw new ClassCastException(activity.toString() + " must implement mainFragmentCallback");

    }

}

}

海新霁
2023-03-14

你应该有你的活动,实现你的接口NoticeDialogListener)。

public class MainActivity extends ActionBarActivity implements
    NoticeDialogListener{

    @Override
    public void onDialogPositiveClick(DialogFragment dialog){
        //Do something
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog){
        //Do some other things
    }

    [...]
}

然后在对话框的按钮单击监听器中,使用mListener调用方法,这些方法现在在活动中实现,代码将在那里执行。

builder.setMessage("Sets")
            .setPositiveButton("set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if(mListener != null)
                            mListener.onDialogPositiveClick(CustomNumberPicker.this);
                    }
            });

还请注意,应该在DialogFragment的onDetach()方法中将mListener设置为null。

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
孔阎宝
2023-03-14

像这样的?

public class CustomNumberPicker extends DialogFragment {
    private NoticeDialogListener ndl;

    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    //add a custom constructor so that you have an initialised NoticeDialogListener
    public CustomNumberPicker(NoticeDialogListener ndl){
        super();
            this.ndl=ndl;
    }

    //make sure you maintain an empty constructor
    public CustomNumberPicker( ){
        super();
    }

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        //remove the check that verfis if your activity has the DialogListener Attached because you want to attach it into your list view onClick()
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Sets")
            .setPositiveButton("set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        ndl.onDialogPositiveClick(dialog);
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                       ndl.onDialogNegativeClick(dialog);
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

然后,listView onClick变为:

tvSets.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // This is where the Dialog should be called and
                    // the user input from the Dialog should be returned
                    // 
                    // 


                    DialogFragment numberpicker = new CustomNumberPicker(new NoticeDialogListener() {

            @Override
            public void onDialogPositiveClick(DialogFragment dialog) {
                //What you want to do incase of positive click

            }

            @Override
            public void onDialogNegativeClick(DialogFragment dialog) {
               //What you want to do incase of negative click

            }
        };);
                    numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
                }

                // Here I would like to implement the interface of CustomNumberPicker
                // in order to get the user input entered in the Dialog
            });

请阅读我添加的评论。它甚至可以进一步优化,因为您真的不需要整个对话框实例来获得所需的值。

编辑可能的优化可能是:

将侦听器界面更改为:

public interface NoticeDialogListener {
        public void onDialogPositiveClick(String output);
        public void onDialogNegativeClick(String output);
       //or whatever form of output that you want
    }

然后相应地修改实现的方法。

 类似资料:
  • 问题内容: 我需要构建一个DialogFragment,它将用户输入从对话框返回到活动。该对话框需要在OnClickListener中调用,当单击列表视图中的元素时会调用该对话框。 DialogFragment的返回值(用户的输入)应在活动的OnClickListener中直接可用。 我尝试通过遵循官方文档来实现此目的:http : //developer.android.com/guide/to

  • 我是android的新手,所以我希望我听起来不会太笨,也就是说,我做了一个片段,专门为XML中的按钮实现了OnclickListener。我需要默认的onclick函数来将按钮的文本保存为字符串,但是我还没有弄清楚如何从视图中检索按钮的文本。这将帮助我为我要做的每一个按钮做一个if语句。有什么建议吗?

  • 问题内容: 如何实现与C#代码等效的Python? 这是一个好主意吗??请在您的答案中举例说明。 问题答案: 正如其他人在这里提到的: 在Python中不需要接口。这是因为Python具有适当的多重继承,还具有鸭式输入法,这意味着 必须 在Java中具有接口的地方,而不必在Python中具有接口。 也就是说,接口还有多种用途。其中一些被Python 2.6中引入的Pythons抽象基类覆盖。如果您

  • 我正在实现一个连接池(JDBC连接和SMPP连接)。我知道有几个经过良好测试的连接池。但我只想自己实现。我在多线程环境中使用它。这更是我个人的兴趣所在。我的实现是这样的。我创建一个ConcurrentLinkedQueue并将连接推送到队列。每次线程请求连接时,都会从队列中弹出连接。作业完成后,线程将连接推回到队列。我的连接轮询实现类如下所示。 我只想知道这个实现有什么问题。请指教。我想为JDBC

  • 问题内容: 如何创建实现此接口的Clojure对象,然后从Java代码调用它? 问题答案: 是实现接口的首选- 重型,较旧且较慢,因此应尽可能避免。一个实现看起来像:

  • 我有一个使用ViewPager的活动,在这个ViewPager中有一个TouchImageView(一个检测手势和相应缩放/移动的ImageView)。 现在,每当单击图像时,我想要更改UI中的一些内容,但因为TouchImageView是在PagerAdapter中声明的,所以我无法访问它,如果我要在PagerAdapter的一侧设置一些内容,我也无法访问我想要更改的UI组件(我还想在应用程序中