我在组件上有片段单击弹出窗口DialogFragment.该对话框片段包含选项列表.当选择列表中的选项时,我想通知片段,以便我可以运行字段更新过程.
我做了这样的事
我做了这样的事
@Override public void onClick(DialogInterface dialog,int item) { updateSharedPreference(item); Log.e("ProfilePersonaListDialog","Click on dialog,inside onClick"); OnCloseListDialogListener act = (OnCloseListDialogListener) getActivity(); act.onDialogListSelection(); dismiss(); }
但是这个getActivity()调用FragmentActivity而不是调用触发对话框片段的片段.
我可以杀死当前打开/运行的片段并调用一个可以获得更新字段的新实例,但这是我希望避免的脏解决方案.
有什么建议如何在对话框片段中选择片段一次更新选项?
解决方法
刚刚回来解决方案.我的问题实际上是转发当前片段getTag()字符串作为DialogFragment的show()参数.如果有兴趣在这里工作样品.
创建简单的侦听器
public interface OnCloseListDialogListener { public void onDialogListSelection(); }
创建将扩展DialogFragment的新对话框
public class ListDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { private PersonaData[] mPersonaData; private String[] mPersonaName; private final String TAG; public static ListDialogFragment newInstance(PersonaData[] personaData,String tag) { ListDialogFragment dialog = new ListDialogFragment(personaData,tag); Bundle bundle = new Bundle(); dialog.setArguments(bundle); return dialog; } private ListDialogFragment(PersonaData[] personaData,String tag) { this.mPersonaData = personaData.clone(); this.TAG = tag; } @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setCancelable(true); int style = DialogFragment.STYLE_norMAL,theme = 0; setStyle(style,theme); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_title); mPersonaName = getData();//Your own implementation here builder.setNegativeButton("Cancel",this); builder.setSingleChoiceItems(mPersonaName,-1,new SingleChoiceListener()); return builder.create(); } @Override public void onClick(DialogInterface dialogInterface,int i) { } private class SingleChoiceListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog,int item) { updateSharedPreference(item); OnCloseListDialogListener act = (OnCloseListDialogListener) getFragmentManager().findFragmentByTag(TAG); act.onDialogListSelection(); dismiss(); } } }
然后在你想要调用此对话框的片段中,如下所示. DIALOG只是String常量我把它放在那里只是对话框
SOME_CLICKABLE.setonClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentManager manager = getFragmentManager(); ListDialogFragment dialog = ListDialogFragment.newInstance(mPersona,getTag()); dialog.show(manager,DIALOG); } });