Android - Multiple colors & size in drawable shape style

▼魔方 西西 提交于 2019-12-07 16:06:44

问题


I'm trying to have a circle background for my TextView, so I created a shape style as below. But I need to have multiple colors with multiple sizes (while the textSize stays constant), so I need to set the width/height in the style.

From my understanding..Layer List puts all the shapes on top of one another? Because I need to call it 12 times at different places, so it seems quite cumbersome to have 12 shape style xmls.

Is there a better way to have all the different shape/size combinations inside one XML?

Shape Style:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval">
    <corners android:radius="10dp"/>
    <solid android:color="@color/girl_orange"/>
        <size
        android:width="84dp"
        android:height="84dp" />
</shape>

Called in layout xml by:

android:background="@drawable/skills_circle"

Thanks in advance!!


回答1:


create a custom Drawable, this way you can have milions combinations of size/color:

class CircleDrawable extends Drawable {
...
}



回答2:


So I followed the advice from pskink and created a CircleDrawable class.

It works quite nicely for my application (although I don't know if it's the right way...), so I thought I'd share it.

public CircleDrawable(Bitmap bitmap, Context context) {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);
    CircleDrawable.context = context;
    drawable = new ShapeDrawable(new OvalShape());
    setColor();  // supports multiple color
    setSize();  //supports multiple size
}

private void setColor() {

     // some algorithm to pick the right color...
    if (...)
        int color = context.getResources().getColor(R.color.pale_blue);

    paint.setColor(color);
}

    /* 
     * algorithm to set size here...
     */

@Override
public void draw(Canvas canvas) {

    //draw circle in the middle of the TextView 
    canvas.drawCircle(textViewSize, textViewSize, circleSize, paint);
}

And in the main code where I need to dynamically draw the circles:

    final float scale = getApplicationContext().getResources().getDisplayMetrics().density;
    int pixels = (int) (107.0f * scale + 0.5f);
    skills.setWidth(pixels);
    skills.setHeight(pixels);
    skills.setBackground(new CircleDrawable(null, getApplicationContext()));

And I ended up with a bunch of circles with different shapes and colors.



来源:https://stackoverflow.com/questions/17754974/android-multiple-colors-size-in-drawable-shape-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!