【发布时间】:2019-06-20 18:46:27
【问题描述】:
在做了许多 hit and try 方法并观察了其他 stackoverflow 代码之后,我能够将数据发送到下一个活动。 我想知道:在 onBindViewHolder 方法中调用 cursor.moveToPosition 两次是否安全。
public class recyclerViewSongAdapter extends RecyclerView.Adapter<recyclerViewSongAdapter.MyViewHolder> {
private final Activity callingActivity;
private final Cursor songCursor;
public recyclerViewSongAdapter(Activity activity, Cursor cursor) {
callingActivity = activity;
songCursor = cursor;
if(songCursor != null) {
songPathIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
songTitleIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
songAlbumIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
}
}
public class MyViewHolder extends RecyclerView.ViewHolder { //implements View.OnClickListener{
public TextView titleTextView, albumTextView;
public View parentLayout;
public MyViewHolder(View view) {
super(view);
titleTextView = view.findViewById(R.id.songTitleId);
albumTextView = view.findViewById(R.id.songAlbumId);
parentLayout = view.findViewById(R.id.parentLinearId);
}
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_element, viewGroup, false);
return new MyViewHolder(itemView);
}
public String songTitle, songAlbum;
int songPathIndex, songTitleIndex, songAlbumIndex;
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int position) {
if(songCursor != null) {
songCursor.moveToPosition(position);
songTitle = songCursor.getString(songTitleIndex);
songAlbum = songCursor.getString(songAlbumIndex);
myViewHolder.titleTextView.setText("" + songTitle);
myViewHolder.albumTextView.setText("" + songAlbum);
myViewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
songCursor.moveToPosition(position);
string title = songCursor.getString(songTitleIndex);
Intent intent = new Intent(callingActivity.getApplicationContext(), SongPlaying.class);
intent.putExtra("mayank", "" + title);
callingActivity.startActivity(intent);
}
});
}
}
@Override
public int getItemCount() {
return (songCursor == null) ? 0 : songCursor.getCount();
}
}
编辑:之前我的问题是如何将点击项目的标题发送到下一个活动,现在我的问题是使用 cursor.moveToPosition 两次,这是个好主意。
【问题讨论】:
-
在
RecyclerViewAdapter内管理游标是一种不好的做法,从Cursor获取ArrayList然后在RecyclerViewAdapter内使用ArrayList -
@Maddy Sir,但是我又如何获得 ArrayList 对象的位置,而且当我在寻找答案时,有很多使用光标的解决方案。先生,我想在不创建任何类和数组列表的情况下做到这一点。
-
在当前场景中,您的光标始终保持打开状态并且您正在邀请此issue
-
@Maddy 谢谢我忘了这样做。但是我不能在我的活动中关闭 onDestroy 方法中的光标。
标签: android android-intent onclicklistener android-recyclerview