我刚刚创建了一个回收站视图但它没有工作,所以我在getItemCount上放了一个断点,并且没有调用该方法。我从未见过其他任何人都有这个问题,我相信这是非常明显的事情。这是我的代码。
public class SearchAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> displayList;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
}
}
public class ErrorSearchItem extends ViewHolder {
//this is here if there is no other viewholder
public ErrorSearchItem(View view) {
super(view);
}
}
public class HeaderViewHolder extends ViewHolder {
public HeaderViewHolder(View view) {
super(view);
}
}
@Override
public int getItemViewType(int position) {
return position;
}
public SearchAdapter(ArrayList<Object> displayList) {
this.displayList = displayList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (displayList.get(viewType) instanceof String){
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_search_title, parent, false);
return new HeaderViewHolder(itemView);
}
else{ //this is for if there is an error and no other xml files match
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_error_search_item, parent, false);
return new ErrorSearchItem(itemView);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return displayList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
编辑:片段代码:
private RecyclerView recyclerView;
private SearchAdapter searchAdapter;
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
searchAdapter = new SearchAdapter(categorizedArray);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(searchAdapter);
答案 0 :(得分:3)
我知道这完全是胡说八道,但对我来说,当我将RecylerView layout_width和layout_height属性从match_parent更改为wrap_content时,问题就解决了。
答案 1 :(得分:3)
在应用适配器之前添加16
答案 2 :(得分:2)
@Mohammed 的回答帮助我意识到我需要设置一个 LayoutManager,但我很困惑,因为我看过一个包含 RecyclerView 实现的自动生成的项目,但它没有设置布局管理器。
我发现您也可以在 xml 中设置布局管理器:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
>
</androidx.recyclerview.widget.RecyclerView>