我必須創建一個圓形並隨機繪製它,但我必須以編程方式進行。它必須是這樣的
需要背景的TextView
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 函數
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]
}
您無法在 xml 中更改可繪製形狀的背景顏色。要動態更改形狀的顏色,您必須創建自定義視圖。
我想出了這兩種方法:
方法 1:使用 Canvas 和 Paint 創建自定義視圖。這是一個有用的示例,說明如何以編程方式創建圓形並為其分配顏色。
使用 Canvas 和 Paint 創建 CustomView
在onDraw()
方法上繪製形狀時,您還可以繪製文本。
方法 2:通過擴展 TheView
或其他ViewGroup
類來創建自定義視圖。這是您應該如何做的一個簡單示例。
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
}
}
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen