我正在使用导航抽屉,在其中一个片段中,我创建了一个回收视图。但是,每当我在片段之间切换时,循环视图的内容就会消失。
这是
mainactivity.java
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_image:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ImagesFragment()).commit(); //this contains recycleview
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
drawer.closeDrawer(GravityCompat.START);
return true;
}
ImagesFragment.java
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image,container,false);
rv= (RecyclerView) rootView.findViewById(R.id.book_RV);
//LAYOUT MANAGER
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
GetImage();
return rootView
}
}
所以我的问题是,每当我在个人资料和图片片段之间切换时,图片中的内容就会消失。
答案 0 :(得分:0)
每次创建新片段,而不是重用旧片段。
您可以将片段创建为类中的字段:
ImagesFragment imagesFragment = new ImagesFragment();
ProfileFragment profileFragment = new ProfileFragment();
在switch
内部,您可以重复使用它们:
switch (item.getItemId()) {
case R.id.nav_image:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
imagesFragment
).commit(); //this contains recycleview
break;
case R.id.nav_profile:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
profileFragment)
.commit();
break;
}
您可以将方法分为两种:
首先要做的是选择片段
第二种方法正在处理事务。
显示所选片段(并隐藏其余片段):
public class MainActivity extends AppCompatActivity {
// Create instance of the fragments
ImagesFragment imagesFragment = new ImagesFragment();
ProfileFragment profileFragment = new ProfileFragment();
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Select fragment to show
switch (item.getItemId()) {
case R.id.nav_image:
showFragment(imagesFragment);
break;
case R.id.nav_profile:
showFragment(profileFragment);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
void showFragment(Fragment fragmentToShow) {
// Create transactionns
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// Hide all of the fragments
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
transaction.hide(fragment);
}
if (fragmentToShow.isAdded()) {
// When fragment was previously added - show it
transaction.show(fragmentToShow);
} else {
// When fragment is adding first time - add it
transaction.add(R.id.fragment_container, fragmentToShow);
}
transaction.commit();
}
}