![](/img/trans.png)
[英]Fragment - E/RecyclerView: No adapter attached; skipping layout
[英]Using a RecyclerView inside a Fragment instead of an Activity results in E/RecyclerView: No adapter attached; skipping layout error
我最初在我的 CarActivity class 中創建並使用了 RecyclerView。這工作正常,從數據庫中檢索信息並將其正確顯示在視圖中。 然后,我修改了 CarActivity class,改為使用名為 AllCarsFragment 的新片段,並將 RecyclerView 代碼移至新的 AllCarsFragment 中。
CarActivity 似乎正確地拾取了新片段的布局,但是,沒有顯示任何數據並且 LogCat 顯示以下錯誤: E/RecyclerView: No adapter attached; skipping layout
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);
}
}
AllCarsFragment.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);
}
});
}
}
如果您需要任何進一步的代碼或信息,請告訴我,我會很樂意更新問題。
從您的 CarActivity 代碼看來,您實際上並沒有按照預期的方式將 AllCarsFragment 附加到 CarActivity。 setContentView(R.layout.fragment_all_cars)
行將布局文件設置為 CarActivity 的內容視圖,但這不會將 AllCarsFragment 中的代碼連接到 CarActivity。 為此,您需要在 CarActivity 的onCreate()
中執行附加的一些額外代碼。 在文檔中,查看“將片段添加到活動”部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.