我已经多次实现 RecyclerView 和客户适配器,但由于某种原因我无法让这个显示任何数据。我正在使用改造从 JSON 中输入数据,并在加载后调用 notifyDataSetChanged() ,但它仍然保持空白。我已将其剥离回仅一个文本视图以尝试简化但仍然没有得到任何结果。谁能看到我哪里出错了?
当我调试时,我让 List 包含数据,所以我肯定正确解析了数据,我只是无法在回收器视图中显示它。我什至检查了 loadTrailerList 方法中的 list.size() 并且它有数据。
我的活动 onCreate 方法:
trailerAdapter = new TrailerAdapter(this);
trailerRecyclerView = findViewById(R.id.trailer_recycler_view);
trailerRecyclerView.setLayoutManager(new LinearLayoutManager(this));
trailerRecyclerView.setAdapter(trailerAdapter);
改造 onResponse 方法:
if (response.body() != null) {
trailers = response.body().getTrailers();
}
trailerAdapter.loadTrailerList(response.body().getTrailers());
我的自定义适配器:
public class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.TrailerViewHolder> {
private final List<Trailer> trailerList = new ArrayList<>();
private final TrailerClickListener listener;
public TrailerAdapter(TrailerClickListener listener) {
this.listener = listener;
}
@NonNull
@Override
public TrailerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.trailer_list_item, viewGroup, false);
return new TrailerViewHolder(itemView, this);
}
@Override
public void onBindViewHolder(@NonNull TrailerViewHolder trailerViewHolder, int i) {
trailerViewHolder.trailerTitle.setText(trailerList.get(i).getName());
}
@Override
public int getItemCount() {
return trailerList.size();
}
public void loadTrailerList(List<Trailer> trailers) {
this.trailerList.clear();
if (trailers != null) {
trailers.addAll(trailers);
}
notifyDataSetChanged();
}
class TrailerViewHolder extends RecyclerView.ViewHolder {
final TrailerAdapter trailerAdapter;
private final TextView trailerTitle;
private TrailerViewHolder(@NonNull View itemView, TrailerAdapter trailerAdapter) {
super(itemView);
this.trailerAdapter = trailerAdapter;
trailerTitle = itemView.findViewById(R.id.text_view_trailer_title);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onTrailerClicked(trailerList.get(getAdapterPosition()));
}
});
}
}
}
我的列表项 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_view_trailer_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play Trailer" />
</LinearLayout>
我的活动 XML 中的回收者视图:
<android.support.v7.widget.RecyclerView
android:id="@+id/trailer_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:layout_constraintTop_toBottomOf="@+id/trailer_divider">
</android.support.v7.widget.RecyclerView>
我很感激任何可以为我指明正确方向的人
哦!我刚刚意识到我做错了什么:
在我的适配器中的 loadTrailerList() 方法中,我调用了:
trailers.addAll(trailers);
代替:
trailerList.addAll(trailers);
将项目列表加载到实际的 ArrayList 中!哎呀!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句