我必須創建一個圓形并隨機繪制它,但我必須以編程方式進行。它必須是 這樣的
需要背景的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 中運行函式?
- 有沒有辦法改變形狀可繪制背景顏色而不改變其形狀
uj5u.com熱心網友回復:
您無法在 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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/373137.html
上一篇:在r上的特定條件下禁用按鈕
