我的应用程序包含两个片段(我们称之为A和B)。片段A显示RecyclerView和Fragment B是该Recycler上所选项目的内容。在小屏幕和普通屏幕上,每个片段都显示在其活动上,但是在大屏幕上,两个片段同时显示,所以我希望在多窗格活动中,当用户点击来自RecyclerView的项目时,它会突出显示。我在StackOverflow上发现了很多像这样的问题,但它们不适用于我的适配器。
final FragmentCallback activity;
final FragmentA fragment; //The fragment with the RecyclerView
Cursor cursor;
int idColumnIndex;
int titleColumnIndex;
int balanceColumnIndex;
public MoneyboxesAdapter(FragmentCallback activity, FragmentA frag){
this.activity = activity;
this.fragment = frag;
}
public void swapCursor(Cursor c){
// Method called whenever the data stored on the DB has changed
this.cursor = c; //Updates the current cursor
if(cursor!=null){
cursor.moveToFirst();
idColumnIndex = cursor.getColumnIndex(MoneyboxProvider.COLUMN_MONEYBOX_ID);
titleColumnIndex = cursor.getColumnIndex(MoneyboxProvider.COLUMN_MONEYBOX_TITLE);
balanceColumnIndex = cursor.getColumnIndex(MoneyboxProvider.COLUMN_MONEYBOX_BALANCE);
}
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
CardView v = (CardView) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.moneybox_item, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
// Sets up the views
cursor.moveToPosition(i);
final long id = getItemId(i);
final String moneyboxTitle = cursor.getString(titleColumnIndex);
final float balance = cursor.getFloat(balanceColumnIndex);
viewHolder.title.setText(moneyboxTitle);
viewHolder.balance.setText(balance);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.onLoadMoneybox(id);
//TODO: Show selected on multipane
}
});
}
@Override
public int getItemCount() {
return cursor!=null?cursor.getCount():0;
}
public long getItemId(int position){
// Gets the ID in the DB of a moneybox
cursor.moveToPosition(position);
return cursor.getLong(idColumnIndex);
}
static class ViewHolder extends RecyclerView.ViewHolder{
CardView cardView;
TextView title;
TextView balance;
ImageView threeDots;
public ViewHolder(CardView itemView) {
super(itemView);
cardView = itemView;
title = (TextView) itemView.findViewById(R.id.moneybox_item_title);
balance = (TextView) itemView.findViewById(R.id.moneybox_item_balance);
threeDots = (ImageView)itemView.findViewById(R.id.three_dots_moneybox);
}
}
答案 0 :(得分:1)
为列表项创建一个选择器并设置view.setSelected(true);对于已选择的特定位置,并跟踪选定的最后一个选定视图,如果用户单击新的行项,则将其设置为false。
答案 1 :(得分:1)
class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public ViewHolder(View view) {
// your code
view.setOnClickListener(this)
}
@Override
public void onClick(View v) {
int position = getPosition();
// your changes for changing color
notifyDataSetChanged();
}
}