由于我是android的新手,所以我努力强调Recyclerview单击的或当前的项目。我尝试了一些解决方法,但没有任何帮助。基本上,我想突出显示选定的项目,即使它是从各自的片段中回来的。请检查我的代码并帮助我完成。谢谢。
public class ContentaAdapter extends RecyclerView.Adapter<ContentaAdapter.MyViewHolder> {
Context context;
ArrayList<String> ItemTitle;
ArrayList<String> ItemSource;
public ContentaAdapter(Context context, ArrayList<String> ItemTitle, ArrayList<String> ItemSource) {
this.context = context;
this.ItemTitle = ItemTitle;
this.ItemSource = ItemSource;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items_layout, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.ItemTitle.setText(ItemTitle.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment contentdisplay = new ViewContentFragment();
Bundle bundle=new Bundle();
bundle.putStringArrayList("ItemTitle",ItemTitle);
bundle.putStringArrayList("ItemSource",ItemSource);
bundle.putInt("position",position);
bundle.putInt("ItemCounts",ItemTitle.size());
contentdisplay.setArguments(bundle);
((MainActivity)context).replaceFragment(contentdisplay);
}
});
}
@Override
public int getItemCount() {
return ItemTitle.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ItemTitle;
public MyViewHolder(View itemView) {
super(itemView);
ItemTitle = (TextView) itemView.findViewById(R.id.item_title);
}
}
}
答案 0 :(得分:0)
您需要将isSelected
状态添加到列表项数据模型中并对其进行更改onClick
。
知道状态后,您可以在ViewHolder
中更改背景
if (isSelected) {
// set selected background here
} else {
// set not selected background here
}
并且不要在适配器中保留两个列表,而应使用类似于以下内容的模型ArrayList<DataModel>
创建一个列表:
class DataModel {
String ItemTitle;
String ItemSource;
Boolean isSelected;
}
您也不应该将两个列表都传递给其他片段,而应仅取所需的内容,例如yourList.get(position);