Home > Blockchain >  How to set a views shape and background color programatically?
How to set a views shape and background color programatically?

Time:12-06

I have to create a circle shape and paint it randomly but I have to do it programmatically. It has to be look like this

TextView that needs background

val tvAuthorSubtext = TextView(context)
tvAuthorSubtext.apply {
   text = "AA"
   textSize = 10f
   setTextColor(ContextCompat.getColor(context, R.color.white))
   gravity = Gravity.CENTER
   typeface = ResourcesCompat.getFont(context, R.font.ubuntu)
   layoutParams = LinearLayout.LayoutParams(72, 72)
   setBackgroundResource(R.drawable.bg_author_shape)
   }

R.drawable.bg_author_shape

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
   <corners android:radius="12dp" />
   <solid android:color="@color/black" />
</shape>

getBackgroundRandomColor Function

fun getRandomBackgroundColor() :Int {
  val colorArray : MutableList<Int> = mutableListOf()
  colorArray.add(R.color.aqua)
  colorArray.add(R.color.bright_blue)
  colorArray.add(R.color.bright_purple)
  colorArray.add(R.color.bright_pink)
  colorArray.add(R.color.bright_green)
  colorArray.add(R.color.orangey_yellow)
  colorArray.add(R.color.tealish)

  val rnds = (0..(colorArray.size-1)).random()

  return colorArray[rnds]

}
  1. Is there any way to run functions in drawable xmls?
  2. Is there any way to change shape drawable background color without changing its shape

CodePudding user response:

You can't change the background color of your drawable shape in xml. For dynamically changing the color of your shape you have to create custom views.

I came up with these two approaches :

Approach Number 1 : Creating Custom View using Canvas And Paint. Here is an useful example of how to create Circle shape programmatically and assign color to it.

Creating CustomView using Canvas And Paint

you can also draw Text when drawing your shape on onDraw() method.

Approach Number 2 : Creating Custom View by extending The View or other ViewGroup Classes. Here is a simple sample of the way you should doing it.

public class ColorOptionsView extends View {

private View mValue;
private ImageView mImage;

public ColorOptionsView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.Options, 0, 0);
    String titleText = a.getString(R.styleable.Options_titleText);
    int valueColor = a.getColor(R.styleable.Options_valueColor,
            android.R.color.holo_blue_light);
    a.recycle();

    // more stuff
}

}

  • Related