Regnodulous
Regnodulous

Reputation: 493

How to create a custom button shape class

I'm editing this to explain that I was trying to create a button as part of a widget with rounded corners that could change its colour programmatically to any colour. When I do this currently using SetInt the default shape of the button changes back to a rectangle. It would appear that the usual ways of achieving this within an activity are not supported for RemoteViews so this question may be unanswerable. Thank you to Mike anyway for pointing this out.

I wonder if this is simple. I want to create a new button class - which is basically just a normal button with rounded corners. The reason for this is that I want to be able to programmatically change the background colour of the button to anything using...

mybutton.setBackgroundColor(Color.parsecolor(somehexvalue));

without the button losing its shape (i.e. reverting to a rectangle).

I have created my button class and understand I need to overwrite the OnDraw method but don;t really understand how I then apply a custom shape at this point. Is this simple?

@RemoteView
public class custombutton extends       android.support.v7.widget.AppCompatButton {

    Paint paint = null;

    public custombutton(Context context) {
        super(context);

        paint = new Paint();
    }

    public custombutton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

public custombutton(Context context, AttributeSet attrs, int defStyle)         {
        super(context, attrs, defStyle);
    }


@Override
protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        What do I need to do here to create a button with rounded corners???

    }

}

Thank you!!!!

Upvotes: 1

Views: 152

Answers (1)

Abhay Koradiya
Abhay Koradiya

Reputation: 2117

You don't need of Customview for this.

Instead of setBackgroundColor, retrieve the background drawable when you need to change background, and set its color:

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

Upvotes: 2

Related Questions