简体   繁体   English

如何创建自定义按钮形状类

[英]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. 当我当前使用SetInt执行此操作时,按钮的默认形状会变回矩形。 It would appear that the usual ways of achieving this within an activity are not supported for RemoteViews so this question may be unanswerable. 看来,RemoteViews不支持在活动中实现此目的的常用方法,因此此问题可能无法回答。 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 (ie 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. 我已经创建了按钮类,并且了解我需要覆盖OnDraw方法,但是并不能真正理解此时我如何应用自定义形状。 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!!!! 谢谢!!!!

You don't need of Customview for this. 您不需要Customview。

Instead of setBackgroundColor, retrieve the background drawable when you need to change background, and set its color: 当需要更改背景并设置其颜色时,可以使用setBackgroundColor代替setBackgroundColor:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM