如何为Button

时间:2017-02-01 04:27:10

标签: java android android-layout android-xml android-shape

如何为Button创建自定义形状?在许多情况下,我可以为按钮背景颜色设置不同的颜色。感谢任何帮助。谢谢。enter image description here

2 个答案:

答案 0 :(得分:3)

  

如何为Button创建自定义形状?

在drawable中创建一个test.xml文件并添加代码:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/one">       //<---- id is must for color change
    <shape android:shape="rectangle">
        <size
            android:width="150dp"
            android:height="40dp" />
        <solid android:color="@color/colorPrimary" />
        <corners android:radius="10dp"/> //<---- remove radius if not needed
    </shape>
</item>

<item
    android:top="10dp"
    android:bottom="-12dp"
    android:left="-55dp"
    android:width="75dp">
    <rotate
        android:fromDegrees="-47">
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
        </shape>
    </rotate>
</item>
</layer-list>

按钮:

     <Button
        .....
        android:background="@drawable/test"
        ...../>
  

输出

enter image description here

  

在许多情况下,我可以为按钮背景颜色设置不同的颜色吗?

是的,您可以在运行时更改。为此,您必须为每个项目分配ID以了解您要进行更改的位置。正如我在答案代码中所做的那样。

LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(Your_Activity.this, R.drawable.your_shape_test);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.id_of_drawable-one);
gradientDrawable.setColor(your_color);

答案 1 :(得分:1)

试试这段代码:

enter image description here

public class ButtonBackGroundDrawable extends Drawable {
private Paint paint;

public ButtonBackGroundDrawable() {
    paint = new Paint();
    paint.setAntiAlias(true);
}

@Override
public void draw(Canvas canvas) {

    int height = getBounds().height();
    int width = getBounds().width();
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    Point point0_draw = new Point(0, 0);
    Point point1_draw = new Point(width, 0);
    Point point2_draw = new Point(width, height);
    Point point3_draw = new Point(0, height);
    Point point4_draw = new Point(width / 10, height / 2);

    Path path = new Path();
    path.moveTo(point0_draw.x, point0_draw.y);
    path.lineTo(point1_draw.x, point1_draw.y);
    path.lineTo(point2_draw.x, point2_draw.y);
    path.lineTo(point3_draw.x, point3_draw.y);
    path.lineTo(point4_draw.x, point4_draw.y);
    path.lineTo(point0_draw.x, point0_draw.y);
    path.close();
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(Color.CYAN);
 //        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawPath(path, paint);
}

@Override
public void setAlpha(int alpha) {
    paint.setAlpha(alpha);
}

@Override
public void setColorFilter(ColorFilter colorFilter) {
    paint.setColorFilter(colorFilter);
}

@Override
public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}
}