上面的答案可能/可能不正确,但最佳实践始终允许通过包含各自 Fragment的Activity进行交易。
在你的 Fragment 中使用 interfaces、onAttach() 来调用封闭的 Activity 和从活动中,允许另一个活动/片段事务。
示例代码如下所示:
public class MyFragmentExample extends Fragment{
//Creating instance of Interface
AnyInterfaceName anyInterfaceName;
/*
This onAttach is responsible for attaching the interface
listener of fragment to Activity
*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
anyInterfaceName = (AnyInterfaceName) context;
} catch (ClassCastException ex) {
throw new ClassCastException(ex.getMessage() + "must implement AnyInterfaceName");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return view;
}
// Define an interface with any name
public interface AnyInterfaceName{
/*
you can give any name to this function & this
function will be implemented later in activity
*/
void startAnotherActivity();
}
}
现在在 Activity 方面:在 extends Activity/AppCompActivity
之后添加它
实现 MyFragment.AnyInterfaceName
在此之后,只需在方法内实现 方法 &,允许在使用 Intent 从 Activity 中转换到另一个 Activity。
注意:
当您想要启动另一个活动时,不要忘记调用片段中的接口。简单地这样称呼它:
anyInterfaceName.startAnotherActivity();
这可能是一项漫长的工作,但为了最佳实践,确实如此。
从官方 android 网站查看 与 Activity 通信 here
希望对你有帮助!!