我正在尝试在片段内使用RecyclerView。但是,一旦我完成代码,适配器中的contex就会显示错误。
在功能onCreateViewHolder()
中,context
显示错误:
from (android.content.Context) in layoutInflator cannot be applied to (com.practice.musicplayer.libraryfragment)
public class SongCardAdapter extends RecyclerView.Adapter<SongCardAdapter.viewHolder> {
private ArrayList<SongCardModel> list;
private LibraryFragment context;
public SongCardAdapter(ArrayList<SongCardModel> list, LibraryFragment context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.libray_recycler_view_layout, parent, false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull viewHolder holder, int position) {
SongCardModel model = list.get(position);
holder.albumArt.setImageResource(model.getImage());
holder.songName.setText(model.getSongName());
}
@Override
public int getItemCount() {
//setting the size of the recyclerView to the size of the list
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
ImageView albumArt;
TextView songName;
public viewHolder(@NonNull View itemView) {
super(itemView);
albumArt = itemView.findViewById(R.id.album_art);
songName = itemView.findViewById(R.id.song_name);
}
}
}
对于崩溃日志
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at com.practice.musicplayer.LibraryFragment.onCreateView(LibraryFragment.java:27)
第27行,我有此代码:
libraryRecyclerView = (RecyclerView)libraryRecyclerView.findViewById(R.id.library_recyclerview);
您可以替换代码中的行吗?>
this.context = context;
with
this.context = context.getContext();
并查看是否有效。
不要在适配器内部传递LibraryFragment,而是传递Context,然后在适配器初始化片段中传递活动。更改您的适配器构造函数:
您必须致电parent.getContext()