我有一个像这样的片段
file_list
我有4个片段,所有这些片段都可以通过底栏使用此方法在MainActivity中切换,当用户点击菜单时,它将用另一个片段替换当前片段(默认:Dashboard):
...
public class Dashboard extends Fragment{
private RecyclerView mTopSellersListView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_dashboard, container, false);
mTopSellersListView = (RecyclerView) view.findViewById(R.id.topSellersListView);
return view;
}
public void setTopSellersListView(MyRecycleAdapter adapter){
mTopSellersListView.setHasFixedSize(true);
mTopSellersListView.setAdapter(adapter);
mTopSellersListView.setLayoutManager(new LinearLayoutManager(getActivity()));
mTopSellersListView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
mTopSellersListView.setItemAnimator(new DefaultItemAnimator());
}
}
我访问另一个类(非活动类)中的setTopSellersListView()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDashboardFragment = new Dashboard();
mOrdersFragment = new Orders();
mProductsFragment = new Products();
mSettingFragment = new Setting();
settingMenu(savedInstanceState);
}
...
public void selectMenu(String menu){
Fragment fr = null;
switch (menu) {
case "Dashboard":
fr = mDashboardFragment;
break;
case "Orders":
fr = mOrdersFragment;
break;
case "Products":
fr = mProductsFragment;
break;
case "Setting":
fr = mSettingFragment;
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
并在mTopSellersListView.setHasFixedSize(true)获得NullPointerExceptions
答案 0 :(得分:0)
首先设置layoutManager而不是使用setHasFizedSize(true)。由于layoutManager确定了recyclerView的大小。
答案 1 :(得分:0)
我已经通过在Fragment中的onStart()中调用setTopSellersListView()来修复它,它运行良好