Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
Lưu dữ liệu fragment khi chuyển sang fragment khác
17:46 19-01-2018
1.036 lượt xem
0 bình luận
19:10 19-01-2018
Làm sao để lưu lại dữ liệu của fragment khi chuyển qua fragment bất kì rồi quay lại vẫn còn dữ liệu ạ. Giống các ứng dụng fb, zalo...
Code trong phần chuyển fragment ạ
private BottomNavigationView bottomNavigationView;
Fragment fragmentCustomer = new customerFragment();
Fragment fragmentdestails = new DetailsFragment();
Fragment fragmentOther = new otherFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//Set default
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main,fragmentCustomer).commit();
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(item.getItemId() == R.id.navigation_customer ) {
setFragment(fragmentCustomer);
return true;
}
else if(item.getItemId() == R.id.navigation_details ){
setFragment(fragmentdestails);
return true;
}
else{
setFragment(fragmentOther);
return true;
}
}
});
}
private void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
String backStateName = fragment.getClass().getName();
String fragmentTag=backStateName;
boolean fragmentPoped = fragmentManager.popBackStackImmediate(backStateName,0);
//Log.e("StateName",backStateName);
Log.e("fragmentPoped",fragmentPoped+"");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(!fragmentPoped){ //create fragment
Log.e("Create fragment name",backStateName);
fragmentTransaction.replace(R.id.main,fragment,fragmentTag);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.addToBackStack(backStateName);
fragmentTransaction.commit();
}else
Log.e("findFragmentByTag",fragmentManager.findFragmentByTag(fragmentTag)+"");
}
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
else{
Log.e("Count Stack",getFragmentManager().getBackStackEntryCount()+"");
super.onBackPressed();
}
}