使用Bundle保存和恢复导航片段状态
在Android的导航片段应用中,当用户旋转或暂时离开应用时,导航状态可能会丢失。为了保留导航状态,可以使用Bundle。Bundle是一个键值存储数据的对象,可以保存导航片段的状态,并在应用重新运行时恢复状态。
下面是保存和恢复导航片段状态的示例代码:
在导航片段的onSaveInstanceState方法中保存状态:
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("selectedItemId", selectedItemId);
}
在导航片段的onCreateView方法中恢复状态:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_navigation, container, false);
BottomNavigationView bottomNavigationView = view.findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
// Restore selectedItemId from saved state
if (savedInstanceState != null) {
selectedItemId = savedInstanceState.getInt("selectedItemId");
bottomNavigationView.setSelectedItemId(selectedItemId);
} else {
// Default selection
bottomNavigationView.setSelectedItemId(R.id.home);
}
return view;
}
使用Bundle保存和恢复导航片段状态,可以保留导航状态并提供更好的用户体验。