美好的一天,我从我的应用程序中的数据库获取信息,并设法将CursorAdapter打包到RecyclerView中,如建议here 但我似乎无法获得开关的位置。我总是从ViewHolder或Cursor返回最后一个项目位置而不是所选位置。这是我的代码:
public class ActionRecyclerAdapter extends RecyclerView.Adapter<ActionRecyclerAdapter.ViewHolder> {
CursorAdapter mCursorAdapter;
Context mContext;
//Cursor cursor;
int position;
ViewHolder holder;
public ActionRecyclerAdapter(final Context mContext, Cursor cursor) {
this.mContext = mContext;
mCursorAdapter = new CursorAdapter(mContext,cursor, 0) {
/* @Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.action_list_items, parent, false);
}
convertView.setTag(position);
return super.getView(position, convertView, parent);
}*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.action_list_items, parent, false);
TextView name = (TextView)view.findViewById(R.id.title_id);
TextView details = (TextView)view.findViewById(R.id.items_details_id);
Switch switch = (Switch)view.findViewById(R.id.item_switch_id);
return view;
}
@Override
public void bindView(View view, final Context context, final Cursor cursor) {
holder = (ViewHolder)view.getTag();
holder.name.setText(cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseModule.KEY_NAME)));
holder.details.setText(cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseModule.KEY_TIME)));
//position=(Integer) view.getTag();
holder.switch.setOncheckListener(new Switch.OnCheckListener() {
@Override
public void onCheck(boolean b) {
if(b){
//holder.timer_switch.getTag();
//position returned is wrong
Toast.makeText(context, "item position" + holder.getAdapterPosition() + "is checked",
Toast.LENGTH_SHORT ).show();
}
}
});
}
};
}
@Override
public int getItemCount() {
return mCursorAdapter.getCount();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
mCursorAdapter.getCursor().moveToPosition(position);
// holder.setDataPosition(position);
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = mCursorAdapter.newView(mContext,mCursorAdapter.getCursor(),parent);
// ViewHolder holder = new ViewHolder(v);
holder = new ViewHolder(v);
v.setTag(holder);
return holder;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View v1;
TextView name;
TextView details;
Switch switch;
int position;
public ViewHolder(View itemView) {
super(itemView);
//v1 = itemView.findViewById(R.id.v1);
}
// public void setDataPosition(int position){
// this.position = position;
// }
// public int getDataPosition(){
// return position;
//}
}
}
我甚至尝试在Viewholder中设置位置,但没有运气。我想如何从Viewholder或光标获取当前位置。非常感谢