【发布时间】:2017-06-28 15:56:21
【问题描述】:
我对 android 编程相当陌生,所以请多多包涵。我已经尝试过搜索 SO、tutorialspoint、big nerd 牧场等,但我没有找到/理解这一点:如何在用户按下主页或概览按钮后使片段持续存在?例如:
我在一个活动中有两个片段 A 和 B,带有一个用于在两个片段之间切换的切换按钮。默认情况下,在创建活动时,片段 A 会加载到屏幕上。如果我切换到片段 B 并按主页或概览,然后返回应用程序,则会显示片段 A。我明白它为什么显示,但我不明白如何保持片段 B 显示。
我已经阅读了有关 backstack、savedInstanceState 和 setRetainInstance(以及其他几个)的信息,但无法弄清楚。
我将在两个片段中覆盖onAttach(Context context)、onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) 和onViewCreated(View view, Bundle savedInstanceState),并在我的活动中覆盖onStart() 和onCreate(Bundle savedInstanceState)。
片段:
@Override
public void onAttach(Context context) {
this.context = context;
faContext = (FragmentActivity) context;
super.onAttach(context);
}// end onAttach(Activity activity)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(bundle != null) {
String bundleAdminId = getString(R.string.bundle_admin_name);
adminName = bundle.getString(bundleAdminId);
}
else {
Log.d("BUNDLE_Profile", "bundle is null");
}
// Defines the xml file for the fragment
return inflater.inflate(R.layout.fragment_profile, parent, false);
}// end onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
onViewCreated 只有按钮事件处理程序
活动:
@Override
public void onStart() {
super.onStart();
// start the home fragment
createFragment(new HomeFragment(), R.id.frag_container);
// update the local storage
}// end onStart()
private void createFragment(Fragment fragment, int fragContainerId) {
// make sure the passed fragment isn't null
if(fragment != null) {
FragmentTransaction ft = faContext.getSupportFragmentManager().beginTransaction();
ft.replace(fragContainerId, fragment);
ft.commit();
}
}// end createFragment(Fragment fragment)`
onCreate 也有按钮处理程序
【问题讨论】:
-
为什么不在 OnCreate 方法中创建片段?