我正在设计一个应用,该应用在homeActivity上具有4个不同的片段,并使用bottomNavigation在它们之间进行切换;在我用作新闻供稿的首页上,这些项目不会显示,直到我切换到另一个片段,然后再次回来。我了解在SO上存在与此类似的问题,但就我而言似乎没有解决方案。 我认为问题与片段中onCreate()和onCreateView的差异有关。
感谢您的帮助。
public class HomeFragment extends Fragment {
View v;
private RecyclerView recyclerView;
private List<Drink> drinksList;
RecyclerViewAdapter recyclerViewAdapter;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_home, container, false);
return v;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drinksList = new ArrayList<>();
drinksList.add(new Drink("Latte",999,"Coffee","test",1.99,77,R.drawable.latte));
drinksList.add(new Drink("Black Tea",123,"Tea", "test", 1.50,11,R.drawable.blacktea));
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = v.findViewById(R.id.recyclerView);
recyclerViewAdapter = new RecyclerViewAdapter(drinksList,getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
}
编辑 添加HomeActivity
public void setUpMenuNav(){
mMainFrame = findViewById(R.id.mainFrame);
bottomNavigationView = findViewById(R.id.bottomNaviationView);
homeFragment = new HomeFragment();
socialFragment = new SocialFragment();
trackingFragment = new TrackingFragment();
locationFragment = new LocationFragment();
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navHome:
setFragment(homeFragment);
return true;
case R.id.navSocial:
setFragment(socialFragment);
return true;
case R.id.navTracking:
setFragment(trackingFragment);
return true;
case R.id.navLocation:
setFragment(locationFragment);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainFrame, fragment);
fragmentTransaction.commit();
}
然后在onCreate()方法中调用setUpMenuBar
答案 0 :(得分:1)
onCreate()
的{{1}}方法上添加HomeActivity
。
应该可以解决问题的。