#android #android-fragments #android-recyclerview #fragment
#Android #android-фрагменты #android-recyclerview #фрагмент
Вопрос:
Я создавал приложение, которое использует a recyclerView
в a Fragment
, но содержимое recyclerView
не отображалось. Он показывает:
'No adapter attached; skipping layout'.
Рекомендуемый вспомогательный класс:
public class FeaturedHelperClass {
int image;
String title;
public FeaturedHelperClass(int image, String title) {
this.image = image;
this.title = title;
}
public int getImage() {
return image;
}
public String getTitle() {
return title;
}
}
Фрагмент:
RecyclerView.Adapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
featuredRecycle = inflater.inflate(R.layout.fragment_dashboard, container, false).findViewById(R.id.explore_recycle);
recycle();
return inflater.inflate(R.layout.fragment_dashboard, container, false);
}
private void recycle(){
featuredRecycle.setHasFixedSize(true);
featuredRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
ArrayList<FeaturedHelperClass> featuredLocations = new ArrayList<>();
featuredLocations.add(new FeaturedHelperClass(R.drawable.mcdonald, "Mcdonald's"));
featuredLocations.add(new FeaturedHelperClass(R.drawable.kfc, "KFC"));
featuredLocations.add(new FeaturedHelperClass(R.drawable.starbucks, "Starbucks"));
adapter = new FeaturedAdapter(featuredLocations);
featuredRecycle.setAdapter(adapter);
}
Комментарии:
1. Ваших данных и кодов недостаточно. опубликуйте свой fragment_dashboard.xml . и объясните, почему ваш надувной функциональный велосипед и ваш фрагмент раздельно?
Ответ №1:
Причина 'No adapter attached; skipping layout'.
того, что после просмотра адаптер представления ресайклера не подключен.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
featuredRecycle = inflater.inflate(R.layout.fragment_dashboard, container, false).findViewById(R.id.explore_recycle);
recycle();
return inflater.inflate(R.layout.fragment_dashboard, container, false);
}
потому что метод recycle() будет выполнен до раздувания представления.
мы можем превратить это в
//inflate the view and return
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
return view;
}
//this callback is just after once the view get inflated in the screen
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
featuredRecycle = view.findViewById(R.id.explore_recycle);
recycle();
}
теперь мы получим featuredRecycle
представление, и будет выполнена логика recycle(), будет отрисован ресайклер.
Ответ №2:
Ваша инфляционная логика кажется ошибочной, попробуйте изменить следующее в вашем onCreateView
featuredRecycle = inflater.inflate(R.layout.fragment_dashboard, container, false).findViewById(R.id.explore_recycle);
recycle();
return inflater.inflate(R.layout.fragment_dashboard, container, false);
в
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
featuredRecycle = view.findViewById(R.id.explore_recycle);
recycle();
return view;
Ответ №3:
Приведенное ниже будет работать для вас, но это не очень хороший подход для задержки расширения представления во фрагменте. Поскольку вы выполняете некоторые задачи перед возвратом представления, это задерживает расширение представления.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
featuredRecycle = view.findViewById(R.id.explore_recycle);
recycle()
return view;
}
Оптимальным подходом было бы выполнение следующего,
//inflate the view and return
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
return view;
}
//this callback is just after the view inflation, you set your ui here
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
featuredRecycle = view.findViewById(R.id.explore_recycle);
recycle()
}
Комментарии:
1. вместо getView() мы можем использовать само представление. по сути, оба будут давать только раздутое представление.