gpt4 book ai didi

android - setColorFilter 更改按钮颜色无效

转载 作者:行者123 更新时间:2023-11-29 20:07:46 26 4
gpt4 key购买 nike

我的应用程序布局中有几个按钮,我想动态更改这些按钮的颜色。当我使用

b.setBackgroundColor(0xFF386F00);

颜色按预期变化,但按钮的形状、大小和填充也发生变化,如 this相关问题。

我尝试使用该答案中建议的解决方案,但是正在做

b.getBackground().setColorFilter(0xFFFF0000,PorterDuff.Mode.MULTIPLY);

对我的任何按钮都没有影响。我不知道这可能是什么原因。相关代码是这样的:

import android.widget.Button;

...

@Override
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View rowView = inflater.inflate(R.layout.hrlistitems, parent, false);

Button b = (Button) rowView.findViewById(R.id.HRlistB);
b.setOnClickListener(onBButtonClicked);
b.getBackground().setColorFilter(0xFFFF0000,PorterDuff.Mode.MULTIPLY);
rowView.setTag(values.get(i).getId());

TextView textView = (TextView) rowView.findViewById(R.id.HRlisttext);
textView.setText(values.get(i).toTitle());

return rowView;

}

这是自定义适配器的一部分,这可能会使事情复杂化,但我也尝试了所有我在“正常”按钮上尝试过的方法,但没有得到积极的结果。适配器中的其他所有内容也完全符合我的预期。

这是对应xml文件的按钮部分

<Button
android:id="@+id/HRlistB"
android:layout_width="30dp"
android:layout_height="40dp"
android:layout_above="@+id/HRlist4"
android:layout_toLeftOf="@+id/HRlistB2"
android:layout_toStartOf="@+id/HRlistB3"/>

由于某种原因,此按钮呈现为一个小正方形 (!),周围有一些空间,角是圆角的。我不知道为什么会这样,但我对它的外观很满意。如果设置背景颜色,大小变为实际的 30dpx40dp,没有任何填充,也没有圆角。我正在尝试找到一种方法来改变颜色并保持其余部分不变。

为什么 ColorFilter 不起作用?

如何在不更改此按钮的任何其他内容(如大小等)的情况下为我的按钮着色?

最佳答案

您还没有将过滤后的可绘制对象设置为按钮的背景:

@Override
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.hrlistitems, parent, false);

Button b = (Button) rowView.findViewById(R.id.HRlistB);
b.setOnClickListener(onBButtonClicked);
Drawable buttonBackground = b.getBackground();
if(buttonBackground != null) {
buttonBackground.setColorFilter(0xFFFF0000,PorterDuff.Mode.MULTIPLY);
b.setBackground(buttonBackground);
}

return rowView;
}

但是,老实说,我不明白你问题的第一部分:

the color changes as expected, but the shape, size and padding of the button changes too

我认为您的问题是您使用的是 AppCompat 主题,因此 Button 已更改为 AppCompatButton

在这种情况下,如果您想获得该结果,则必须使用 setBackgroundTintList(ColorStateList tint) 方法。可以找到官方文档here

编辑

我现在看到您的按钮没有背景,您不能使用 ColorFilter 来更改它,因为 Drawable 为 null。

关于android - setColorFilter 更改按钮颜色无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com