0

добрый вечер, не могу понять почему во фрагменте не отображается recyclerview. если надо код скину

public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.CategoriesViewHolder> {

    private ArrayList<Category> categoryList;
    private onCategoriesPositionClick onCategoriesPositionClick;

    public CategoriesAdapter (ArrayList<Category>categoriesList, onCategoriesPositionClick onCategoriesPositionClick){
        this.categoryList = categoriesList;
        this.onCategoriesPositionClick = onCategoriesPositionClick;
    }

    @Override
    public CategoriesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_categories, null);
        return new  CategoriesViewHolder (view);
    }

    @Override
    public void onBindViewHolder(CategoriesViewHolder holder, int position) {

        holder.category.setText(categoryList.get(position).getCategory());
        holder.image_ic.setImageResource(categoryList.get(position).getImage_ic());

    }

    @Override
    public int getItemCount() {
        return categoryList.size();
    }


     class CategoriesViewHolder extends RecyclerView.ViewHolder {

        TextView category;
        ImageView image_ic;
        LinearLayout linearlayout;

        public CategoriesViewHolder(View itemView) {
            super(itemView);

            category = (TextView)itemView.findViewById(R.id.Category);
            image_ic = (ImageView)itemView.findViewById(R.id.Image_ic);
            linearlayout = (LinearLayout) itemView.findViewById(R.id.Category_linearLayout);

            linearlayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onCategoriesPositionClick.OnCategoriesClick(getAdapterPosition());

                }
            });

        }
    }
}

public class FragmentCategories extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_Category = "param1";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

RecyclerView.LayoutManager mLayoutManager;
private RecyclerView recyclerView;
private CategoriesAdapter categoriesAdapter;
ArrayList<Category>categoryList = new ArrayList<>();

private onCategoryPositionSelectedListener mListener;

public FragmentCategories() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @return A new instance of fragment FragmentCategories.
 */
// TODO: Rename and change types and number of parameters

public static FragmentCategories newInstance(ArrayList<Category> categoryList) {
    FragmentCategories fragmentCategories = new FragmentCategories();
    Bundle args = new Bundle();
    args.putSerializable(ARG_Category,categoryList);
    fragmentCategories.setArguments(args);
    return fragmentCategories;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    if (getArguments() != null)
        categoryList = (ArrayList<Category>) getArguments().getSerializable(ARG_Category);
}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_categories, container, false);

         recyclerView = view.findViewById(R.id.rv_categories);
         recyclerView.setHasFixedSize(true);
         categoriesAdapter = new CategoriesAdapter(categoryList, new onCategoriesPositionClick() {
             @Override
             public void OnCategoriesClick(int position) {
                 mListener.onCategoryPositionClick(position);
             }

            });
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
            recyclerView.setLayoutManager(llm);
            recyclerView.setAdapter(categoriesAdapter);

            return view;
        }



@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof onCategoryPositionSelectedListener) {
        mListener = (onCategoryPositionSelectedListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}


@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
    public interface onCategoryPositionSelectedListener {
        // TODO: Update argument type and name

        void onCategoryPositionClick(int position);
    }
}
3

1 ответ 1

1

Вы неправильно инфлейтите разметку в onCreateViewHolder Надо так:

View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_categories, parent, false);

Почему так?

Сейчас вы передаете в качестве контейнера null. Поэтому ваша View не прикрепляется к нему. В onCreateViewHolder приходит контейнер, к нему и надо подключить вашу View

15
  • спасибо, точно не заметила, но все равно не работает(
    – лена
    22 дек 2017 в 22:04
  • @лена, попробуйте убрать setHasFixedSize
    – user194625
    22 дек 2017 в 22:05
  • убрала,не помогло(
    – лена
    22 дек 2017 в 22:11
  • @лена, обновил ответ
    – user194625
    22 дек 2017 в 22:11
  • @лена, хм.. Попробуйте в newInstance просто сохранять данные в переменную фпагмента fragmentCategories.categoryList = categoryList
    – user194625
    22 дек 2017 в 22:19

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.