【问题标题】:Unable to attach adapter for recycler view in fragment无法在片段中为回收站视图附加适配器
【发布时间】:2018-09-29 11:22:11
【问题描述】:

在我的应用程序中,我在片段中使用回收站视图。该回收商视图数据来自数据库。我完美地获取了所有数据,但所有数据相互重叠并在日志 cat 中出现错误。我正在使用卡片视图创建每一行回收器视图并使用 volley 库来获取数据。

fragment.java:

public class HomeFragment extends Fragment {

private static final String CATEGORY_URL = "http://192.168.0.101/cart/category/get_all_category.php";

List<Category> categoryList;
RecyclerView recyclerView;
CustomCategoryList customCategoryList;

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

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_home, container,false);

    //getting the recyclerview from xml
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recylcerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    recyclerView.setHasFixedSize(true);

    categoryList = new ArrayList<>();

    loadCategory();

    //customCategoryList = new CustomCategoryList(getActivity(),categoryList);
    return rootView;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

private void loadCategory(){
    StringRequest stringRequest= new StringRequest(Request.Method.GET, CATEGORY_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject obj = new JSONObject(response);
                JSONArray array = obj.getJSONArray("category");
                for (int i = 0; i < array.length(); i++){
                    //getting the user from the response
                    JSONObject userJson = array.getJSONObject(i);

                    categoryList.add(new Category(
                            userJson.getInt("categoryid"),
                            userJson.getString("categoryname")
                    ));
                }
                customCategoryList = new CustomCategoryList(getActivity(),categoryList);
                recyclerView.setAdapter(customCategoryList);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}

fragment.xml:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CATEGORIES : -"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="@color/blue"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylcerView"
        android:layout_below="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="@dimen/activity_horizontal_margin">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

row.xml:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:orientation="vertical"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="5dp">


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/top_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="5dp">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="90dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/home_appliances"
        android:layout_marginLeft="5dp"
        android:gravity="center_vertical"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="5dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/catname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HOME DECORE"
            android:textStyle="bold"
            android:textSize="20sp"
            android:textColor="@color/black"
            android:padding="@dimen/nav_header_vertical_spacing"/>

    </RelativeLayout>

</LinearLayout>

错误:

错误:09-28 20:08:27.991 19249-19249/com.example.arpan.e_cart E/RecyclerView:未连接适配器;跳过布局

适配器类如下:

public class CustomCategoryList extends RecyclerView.Adapter<CustomCategoryList.ViewHolder>{

private Context mCtx;
private List<Category> categoryList;

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView category;

    public ViewHolder (View view) {
        super(view);
        category = view.findViewById(R.id.catname);
    }
}

public CustomCategoryList(Context mCtx, List<Category> categoryList) {
    this.mCtx = mCtx;
    this.categoryList = categoryList;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.custom_category_list,null);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Category category = categoryList.get(position);

    holder.category.setText(category.getCategoryname());
}

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

【问题讨论】:

  • 此错误是否会干扰您的应用,还是会在一段时间后显示列表?
  • 你的适配器代码是什么?
  • 发生错误是因为创建活动时还没有附加适配器(如 MACmist 回答中所述)。进行网络调用后,适配器被设置为回收器视图。 XML 和 Activity 看起来不错,可能问题出在 CustomCategoryList(适配器)
  • 现在错误消失但所有行相互重叠
  • 没有setHasFixedSize可以试试吗?

标签: android android-fragments android-recyclerview


【解决方案1】:

我认为发生此错误是因为您在呈现视图时尚未将适配器添加到您的 recyclerview。

您是否尝试将这两行放在 recyclerview 初始化之后,而不是放在 onResponse 方法中?

customCategoryList = new CustomCategoryList(getActivity(),categoryList);
recyclerView.setAdapter(customCategoryList);

那么在你的 onResponse 中你实际上会这样做:

customCategoryList.notifyDataSetChanged();

将所有数据添加到列表后

【讨论】:

  • 该错误无关紧要。 RecyclerView 在设置适配器时重绘。
  • 感谢回复。它有效,但行与图片相同。相互重叠
  • 您是否尝试过将您的卡片视图移动到具有填充的框架布局中?因为我不确定margin 是否适用于recyclerview 中元素的布局。你也可以尝试在你的 recyclerview 中添加一个物品装饰,见stackoverflow.com/questions/24618829/…
【解决方案2】:

创建这个文件。

CategoryListAdapter.java

public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.ItemHolder> {

    private List<Category> categoryList;
    private Context mContext;

    public CategoryListAdapter(List<Category> categoryList, Context mContext) {
        this.categoryList = categoryList;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

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

        return new ItemHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ItemHolder holder, final int position) {

        // Get each category, one by one.
        Category singleCategory = categoryList.get(position);

        // Set the category content to the layout
        holder.name.setText(singleCategory.getName());
        // Do something with the image. You can load the url using GlideApp
        holder.imageView ... 


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


    // --------------------------------------------------------------------------------
    //                                    ViewHolder
    // --------------------------------------------------------------------------------
    public class ItemHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;

        public TextView name;

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

            imageView = itemView.findViewById(R.id.image_view);

            name = itemView.findViewById(R.id.catname);

        }
    }

}

最后设置recycler view adapter,(设置为Macmist answer)

mRecyclerView.setAdapter(new CategoryListAdapter(categoryList, getActivity()));

【讨论】:

  • 我认为recyclerView.setHasFixedSize(true); 是原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 2022-07-19
相关资源
最近更新 更多