我想为我的 RecyclerView
创建可点击的项目。但是它不起作用。 item_background.xml
定义得很好,它适用于我项目的其他部分。但是在这种情况下,我在 LinearLayout
中有更多项目,其中包含一些 onClick
监听器。当我点击一个 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
}
}
您还可以在 View 持有者中定义父布局点击监听器即线性布局
关于android - 更改 RecyclerView 项目的项目背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359463/