【问题标题】:Android ListView change bg color but leave onclick animationAndroid ListView改变bg颜色但留下onclick动画
【发布时间】:2020-05-17 13:49:01
【问题描述】:

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

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

更新 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"));
        }
``

【问题讨论】:

  • 你能发布你的getView()代码吗?
  • @GiuseppeCriscione 将其添加到主题中

标签: android listview


【解决方案1】:

创建一个可绘制对象: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>

然后你设置drawable而不是颜色, 您可以从适配器或行 xml 设置它。

【讨论】:

  • 我如何知道使用的是什么默认动画?因为我想保留它
【解决方案2】:

更改 onBindViewHolder 中的背景颜色

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

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 2019-04-06
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多