安卓列表视图更改bg颜色,但保留点击动画



我在Android中有ListView,其中包含我的对象。每行的背景色代表对象的状态,所以我想为不同的行使用不同的颜色,但我想有onClick动画。除此之外,有些行具有默认的 bg 颜色,因此我想为它们保留默认的 onClick 动画。

在 ArrayAdapter 中,如果我getView()方法设置背景颜色 - 动画将停止工作。 如何同时拥有动画和非标准 bg 颜色?

更新 1:我的 getView 方法如下所示:


public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {       
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.action_table_row, parent, false);
}
if (conditionIsMet(getItem(position)) {
convertView.setBackgroundColor(Color.parseColor("#f6bcbc"));
}
``

创建一个可绘制对象:res/drawable/mycolor1.xml

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
// onclick
<item android:state_pressed="true">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="4sp" />
<solid
android:color="your_color" />
<stroke
android:width="2sp"
android:color="your_border_color" />
<padding android:top="5sp" android:right="5sp"
android:bottom="5sp" android:left="5sp"/>
</shape>
</item>
// default
<item android:state_enabled="true">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="3sp" />
<solid
//leave it empty if you want default color
/>
<stroke
android:width="2sp"
android:color="your_border_color" />
<padding android:top="5sp" android:right="5sp"
android:bottom="5sp" android:left="5sp"/>
</shape>

然后设置可绘制对象而不是颜色, 您可以从适配器或行 XML 进行设置。

更改onBindViewHolder的背景颜色

public void onBindViewHolder(final ViewHolder holder, final int position) {
if (conditionIsMet(getItem(position)) {
holder.yourLayout.setBackgroundColor(Color.parseColor("#f6bcbc"));
}
}

最新更新