java在片段中使用RecyclerView而不是活动会导致E/RecyclerView:没有连接适配器;跳过布局错误
我最初在我的CarActivity类中创建并使用了一个RecyclerView。这很好,从数据库中检索信息并在视图中正确显示。然后我修改了CarActivity类,改为使用一个名为AllCarsFragment的新片段,并将RecyclerView代码移动到新的AllCarsFragment中
CarActivity似乎正确地拾取了新片段的布局,但是,没有显示任何数据,LogCat显示以下错误:E/RecyclerView: No adapter attached; skipping layout
我尝试过在片段onCreateView和onViewCreated方法之间移动代码,并用其他一些方法处理代码,但是我无法找到修复方法
我也浏览了StackOverflow上类似的问题,但我没有任何进展,所以非常感谢您的帮助
CarActivity。java
public class CarActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_all_cars);
}
}
所有cars片段。java
public class AllCarsFragment extends Fragment {
private static final String LOG_TAG = AllCarsFragment.class.getSimpleName();
private CarViewModel mCarViewModel;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_cars, container, false);
// Set up the recycler view to display the users saved cars
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
final CarListAdapter adapter = new CarListAdapter(view.getContext());
recyclerView.setAdapter(adapter);
mCarViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
mCarViewModel.getAllCars().observe(getViewLifecycleOwner(), new Observer<List<Car>>() {
@Override
public void onChanged(@Nullable final List<Car> cars) {
// Update the cached copy of the cars in the adapter.
adapter.setCars(cars);
}
});
return view;
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Configure the FAB to redirect the user to add a new car
FloatingActionButton fab = view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(LOG_TAG, "Add Car FAB Pressed");
NavHostFragment.findNavController(AllCarsFragment.this)
.navigate(R.id.add_car_dest, null);
}
});
}
}
请让我知道,如果你需要任何进一步的代码或信息,我会很高兴地更新问题
# 1 楼答案
从您的CarActivity代码来看,似乎您并没有按照预期的方式将AllCarsFragment附加到您的CarActivity。行
setContentView(R.layout.fragment_all_cars)
将布局文件设置为CarActivity的内容视图,但这不会将AllCarsFragment中的代码连接到CarActivity。要做到这一点,您需要在CarActivity的onCreate()
中添加一些额外的代码,它执行附加操作。在docs中,查看关于“向活动添加片段”的部分