我寫我的代碼直接使用遊標由於在Populate recyclerview with a SQLite database?的回答以下pskink的評論。做一些研究(基於OnClickListener for RecyclerView問題)和實驗後,我發現,移動setOnClickListener()到ViewHolder和添加的onClick()作爲其方法,我可以訪問的TextView,但沒有得到字符串值。如何訪問在RecyclerView(使用光標)在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);
}
代碼中的onClick住:
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是先前點擊的光標值。再點擊一下後的位置是:8是點擊的TextView和寵物ID的位置:2和寵物名稱:叔是從以前的點擊正上方光標的價值!
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
然而,雖然位置是正確的當前點擊,如何訪問在點擊的TextView的字符串,而不是以前的字符串的指針?
你在哪裏intitialize'mCursor'?你能添加更多的代碼來解決這個問題嗎? – iTurki
iTurki,我編輯我的職務,以顯示你在哪裏mCursor,我相信這是在適配器的構造。 – Jeff