[英]Change item background on RecyclerView item
我想制作我的RecyclerView
可点击项目。 但它不起作用。 item_background.xml
定义得很好,它适用于我项目的其他部分。 但是在这种情况下,我在LinearLayout
有更多项,其中包含一些onClick
侦听器。 当我点击某个item
,背景不会改变。 请参阅下面的代码。
我不能为内部项目设置背景,因为我需要整个项目来改变背景颜色,而不仅仅是部分。
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:background="@drawable/item_background"
android:clickable="true"
...
>
<TextView
<!-- NO BACKGROUND -->
... />
<ImageView
<!-- NO BACKGROUND -->
... />
...
</LinearLayout>
item_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/darker_gray" android:state_pressed="true"/>
<item android:drawable="@android:color/darker_gray" android:state_focused="true"/>
<item android:drawable="@android:color/transparent"/>
</selector>
要在recyclerview
更改背景或突出显示所选项目,您可以尝试此操作
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
private int selected_position = -1;
@Override
public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
if (selected_position == position) {
// do your stuff here like
//Change selected item background
parentLayout.setBackgroundColor(Color.parse("darkgraycolorcode"));
} else {
// do your stuff here like
//Change unselected item background
parentLayout.setBackgroundColor(Color.TRANSPARENT);
}
// rest of the code here
holder.linelayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(selected_position==position){
selected_position=-1;
notifyDataSetChanged();
return;
}
selected_position = position;
notifyDataSetChanged();
}
});
//rest of the code here
}
}
您还可以在视图持有者中定义父布局单击侦听器,即linearlayout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.