[英]How to programmatically change an image button icon's color?
我有一个带图标的imageButton:
<ImageButton
android:src="@drawable/ic_action_favorite"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/discussionActionBtn"/>
当前,图标的默认颜色是灰色。 是否可以通过编程方式使图标以其他颜色显示?
到目前为止,我能想到的最好的办法就是用所需的颜色创建另一个资产,但是我想知道是否还有另一种方法(也许使用滤镜?)
<Button
android:background="@android:color/white"
android:textColor="@android:color/black"
/>
或通过编码btnSample.setBackgroundColor(Color.WHITE); btnSample.setTextColor(Color.BLACK);
如果要以编程方式进行操作,则可以使用像这样的小类,它为ImageButton
提供了很好的边框。
public class BorderDrawable extends BitmapDrawable {
private static final int BORDER_WIDTH = 9;
private final int[] GRADIENT_COLORS = {Color.GRAY,Color.BLUE, Color.GREEN, Color.RED};
Paint borderPaint;
public BorderDrawable(Resources res, Bitmap bitmap) {
super(res, bitmap);
this.borderPaint = new Paint();
borderPaint.setStrokeWidth(BORDER_WIDTH);
borderPaint.setStyle(Paint.Style.STROKE);
// set border gradient
Shader shader = new LinearGradient(0, 0, 0, getBounds().bottom, GRADIENT_COLORS, null, Shader.TileMode.CLAMP);
borderPaint.setShader(shader);
// or the border color
// borderPaint.setColor(Color.GREEN);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// draw
canvas.drawRect(getBounds(), borderPaint);
}
}
您可以像这样使用它。
Bitmap bmp = /*your bitmap*/;
BorderDrawable drawable = new BorderDrawable(getResources(), bmp);
discussionActionBtn.setImageDrawable(drawable);
希望我不会离开主题。我想这可以为您提供帮助。
Drawable img = mContext.getDrawable(R.drawable.ic_icon);
img.setTint(Color.parseColor(myColor));
btnOne.setBackground(img);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.