由于pskink在回答下面的评论,我编写了直接使用光标的代码
Populate recyclerview with a SQLite database?
OnClickListener for RecyclerView
问题)和实验我发现,将setOnClickListener()移动到ViewHolder并添加onClick()作为其方法,我可以访问TextView,但无法获得字符串值。
mCursor已初始化:
public SelectPetNameAdapter(Context context, Cursor cursor) {
this.mContext = context;
mCursor = cursor;
//TEST: the following is here to verify that the Cursor is passed to this class. It is.
int cnt = getItemCount();
Log.d("Cursor count is", " " + cnt);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public View mView;
public ViewHolder(View itemView) {
super(itemView);
Log.d("Instantiating", "ViewHolder");
itemView.setOnClickListener(this);
tvName = (TextView) itemView.findViewById(R.id.petname);
mView = itemView;
}
@Override
public void onClick(View v){
Log.d("Entered", "onClick in ViewHolder");
int mPosition = getLayoutPosition();
String name = mCursor.getString(0);
int rowId = mCursor.getPosition();
Intent intent = new Intent(mContext, PetInformationActivity.class);
long holderId = itemView.getId();
String holderName = itemView.toString();
int viewId = v.getId();
mCursor.moveToPosition(mPosition);
Log.d("Entered", "setOnClickListener in SelectPetNameAdapter");
Log.d("holderId is", " " + holderId);
Log.d("holderName is", " " + holderName);
Log.d("viewId is", " " + viewId);
Log.d("position is", " " + mPosition);
Log.d("Pet ID is", " " + rowId);
Log.d("Pet name is", " " + name);
Bundle extras = new Bundle();
extras.putString(NAME_KEY, name);
intent.putExtras(extras);
mContext.startActivity(intent);
}
}
虽然这确实提供了对TextView字符串的访问,但显示的名称与单击的TextView不同步。如下所示
LOGCAT公司
位置:2
是单击的TextView的位置,但
宠物ID:0
和
宠物名:qwerty
是单击的TextView和
宠物ID:2
宠物名:fert
是上一次单击的光标值!
LOGCAT公司
Entered: onClick in ViewHolder
Entered: setOnClickListener in SelectPetNameAdapter
holderId is: 2131558581
holderName is: android.support.v7.widget.AppCompatTextView{b3adb53 V.ED..C.. ...P.... 0,98-1056,147 #7f0d00b5 app:id/petname}
viewId is: 2131558581
Position is: 2
Pet ID is: 0
Pet name is: qwerty
Entered: onCreate in PetInformatioActivity
petName (from Bundle) is: qwerty
Id (from Bundle) is: null
Entered: onClick in ViewHolder
Entered: setOnClickListener in SelectPetNameAdapter
holderId is: 2131558581
holderName is: android.support.v7.widget.AppCompatTextView{45fe03c V.ED..C.. ...P.... 0,392-1056,441 #7f0d00b5 app:id/petname}
viewId is: 2131558581
Position is: 8
Pet ID is: 2
Pet name is: fert
Entered: onCreate in PetInformatioActivity
petName (from Bundle) is: fert
Id (from Bundle) is: null
但是,虽然当前单击的位置正确,但如何访问已单击文本视图中的字符串,而不是光标中的上一个字符串?