我有一个父片段。单击按钮后,将创建一个子对话框片段。 现在我想知道如何从子对话框片段调用父片段函数。
以下是示例代码:
/**SampleFragment.java**/
public class SampleFragment extends Fragment {
// Instantiate view & add event handlers
public void onButtonClick(....) {
// Create a dialog framgent
}
public void refreshView() {
}
}
/**SampleDialogFragment.java**/
public class SampleDialogFragment extends DialogFragment {
// Instantiate view for dialog
public void onButtonClick(...) {
// Call parent fragment method, i.e call refreshView() of SampleFragment
}
}
答案 0 :(得分:6)
比如你的父片段,例如SettingsFragment。请注意setTargetFragment()
public void onButtonClick(....)
{
PrefLanguageDialogFragment prefLang = PrefLanguageDialogFragment.newInstance();
prefLang.setTargetFragment(SettingsFragment.this, 1337);
prefLang.show(getFragmentManager(), "dialog");
}
在我们的对话框中,请注意getTargetFragment()
SettingsFragment frag = (SettingsFragment)getTargetFragment();
if(frag != null){
frag.refreshSomething();
}
答案 1 :(得分:3)
在片段中:
SampleDialogFragment dialogFragment = new SampleDialogFragment();
dialogFragment.show(getChildFragmentManager());
在DialogFragment中:
((SampleFragment) getParentFragment()).refreshView();
调用此方法后,您可以访问父片段的公共方法。
答案 2 :(得分:0)
如果要为活动添加SampleFragment
,请为其设置标记,例如“SampleFragment”。
然后
public void onButtonClick(...){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment parent = (SampleFragment)fm.findFragmentByTag("SampleFragment");
parent.refreshview();
}
没有测试它,但它可能会有所帮助: - )
答案 3 :(得分:0)
最好的方法是使用接口,在嵌套片段中声明一个接口 -
public interface checkingClickListener { public void checkingClickListener(String data); }
然后将此接口附加到父片段 -
public void onAttachFragment(Fragment fragment)
{
try
{
clickListener = (checkingClickListener) fragment;
} catch (ClassCastException e)
{
throw new ClassCastException(fragment.toString() + " must implement checkingClickListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
this.mContext = getActivity().getApplicationContext();
onAttachFragment(getParentFragment());
....
}
你需要点击一下按钮来调用这个监听器 -
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.tv_submit:
if (clickListener != null)
{
clickListener.checkingClickListener("sending data");
}
break;
}
}
在父片段中实现此接口 -
public class Fragment_Parent extends Fragment implements Nested_Fragment.checkingClickListener
{
....
@Override
public void checkingClickListener(final List<Player> players_list)
{
FragmentManager fragmentManager = getChildFragmentManager();
SomeOtherNestFrag someOtherNestFrag = (SomeOtherNestFrag) fragmentManager.findFragmentByTag([Tag of your fragment which you should use when you add]);
if(someOtherNestFrag != null)
{
// your some other frag need to provide some data back based on views.
SomeData somedata = someOtherNestFrag.getSomeData();
// it can be a string, or int, or some custom java object.
}
}
}
希望这会对你有所帮助。