问题描述
我有一个 listFragment,我想在 listItemClick 上显示一个 DialogFragment(是/否).我想在 listFragment 中取回用户选择(是/否).我已经阅读了有关侦听器接口机制的内容,但它适用于活动 片段.一种方法可以是:
I have a listFragment, where I want to display a DialogFragment (Yes/No) on listItemClick. I want to get back the user selection(Yes/No) in listFragment. I have read about the listener interface mechanism but that work with activity<->fragment. One way of doing this can be:
- 在包含是/否按钮选择函数的对话框片段中定义接口,并在警告对话框正/负按钮点击时调用这些方法.
- 在主活动中实现这个接口.
- 在单击项目时在 listFragment 中启动 dialogFragment.
- 在活动中保存用户选择.
- 通过在主活动中实现的另一个接口在 listFragment 中获取此选项.
但是对于这个简单的任务,我们有什么简单的机制吗?任何示例或代码?
But do we have any simple mechanism for this simple task? any example or code?
推荐答案
还有一种方法可以从 DialogFragment 中获取结果.
您可以使用 Fragment.setTargetFragment().创建 DialogFragment 的实例时,将目标片段设置为它.然后在 DialogFragment 中,您可以从 Fragment.getTargetFragment().
例如,您可以这样做:
There is another way how to get the result back from DialogFragment.
You can use Fragment.setTargetFragment(). When creating an instance of your DialogFragment set target fragment to it. Then in DialogFragment you can get this fragment from Fragment.getTargetFragment().
For example, you can do it so:
public interface DialogClickListener {
public void onYesClick();
public void onNoClick();
}
public class MyListFragment extends ListFragment implements DialogClickListener {
...
private void showDialog() {
DialogFragment dialog = new MyDialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(getFragmentManager(), "dialog");
}
@Override
public void onYesClick() {
// do something
}
@Override
public void onNoClick() {
// do something
}
}
public class MyDialogFragment extends DialogFragment {
private DialogClickListener callback;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
callback = (DialogClickListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement DialogClickListener interface");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("message")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onYesClick();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onNoClick();
}
});
return builder.create();
}
}
这篇关于如何从对话框片段获取主机片段中的按钮点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!