如何以编程方式更改图像按钮图标的颜色?

时间:2014-09-01 20:40:34

标签: android android-layout

我有一个带图标的imageButton:

        <ImageButton
            android:src="@drawable/ic_action_favorite"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:id="@+id/discussionActionBtn"/>

目前,图标的默认颜色为灰色。 有没有办法以编程方式使图标以另一种颜色显示?

到目前为止,我能想到的最好的方法是创建具有所需颜色的另一种资产,但我想知道是否有其他方式(可能使用过滤器?)

3 个答案:

答案 0 :(得分:0)

<Button
android:background="@android:color/white"
android:textColor="@android:color/black"
/>

或通过编码     btnSample.setBackgroundColor(Color.WHITE);     btnSample.setTextColor(Color.BLACK);

答案 1 :(得分:0)

如果您想以编程方式执行此操作,那么您可以使用这样的小类为您的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);

希望我不偏离这个主题。我想这可以帮到你。

答案 2 :(得分:-1)

Drawable img = mContext.getDrawable(R.drawable.ic_icon);
img.setTint(Color.parseColor(myColor));
btnOne.setBackground(img);