隐藏片段容器的更好方法?



noob fragmentmanager问题。有没有更好的方法来关闭一个片段,从一个按钮里面说片段?我试图使用getParentFragmentManager从片段内的onclick,但这似乎不起作用(或做任何事情真的)。我猜,因为我真的需要在主活动的容器被隐藏,而不是片段?我确实有一个工作视图模型,想知道是否在主活动中运行一个协同例程会更好,该活动会监听按钮单击并隐藏/显示容器视图中的片段。请记住,我在主活动中有多个容器视图。

parentFragmentManager.beginTransaction().hide(this).commit()

我们可以使用supportFragmentManager而不是parentFragmentManager(如果不使用fragment inside fragment)猜测你的活动是AppCompat 1。

activity.supportFragmentManager.beginTransaction().hide(this).commit()

或者如果你想弹出你的片段,那么你可以这样做:

activity.supportFragmentManager.popBackStack()
要隐藏活动,我们可以使用fragmentlistener回调。它是一种回调:
public class MyActivity implements OnFragmentInteractionListener {
@Override
public void onFragmentInteraction(String pageClassName, int operationCode, Bundle operationRequirement) {
//here we can put conditions if any according to pageClassName or operationCode
}
}
public interface OnFragmentInteractionListener {
/**
* @param pageClassName This basically class.getName() string eg.Myfragment.this.getClass().getName()
* @param operationCode This would be an we are using to distinguish each opearation
* @param operationRequirement This would be bundle that would contain result
* */
void onFragmentInteraction(String pageClassName, int operationCode, @Nullable Bundle operationRequirement);
}

现在在我的片段中:

private OnFragmentInteractionListener mListener;

@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) mActivity;
} catch (ClassCastException e) {
throw new ClassCastException("activity must implement OnFragmentInteractionListener");
}
}

现在inside onClick of fragment:

mListener.onFragmentInteraction(TAG, HIDE_FRAMENT, extras);

导航组件似乎是管理片段事务的最佳方式(对于我的用例)。工作与绑定也!

https://developer.android.com/guide/navigation

最新更新