写一个区别于原生的自定义<TextView>,用kotlin实现,需要代码注释
时间: 2023-06-09 22:03:40 浏览: 64
好的,我来回答你的问题,以下是代码注释:
```
// 定义一个自定义 TextView 类,继承系统原生的 TextView
class CustomTextView(context: Context, attrs: AttributeSet? = null) : TextView(context, attrs) {
// 自定义属性变量,用于在 XML 中定义自定义属性
private var customText: String = ""
init {
// 初始化操作
attrs?.let {
// 解析 XML 中自定义属性的值,并赋值给自定义属性变量
val typedArray = context.obtainStyledAttributes(it, R.styleable.CustomTextView)
customText = typedArray.getString(R.styleable.CustomTextView_customText).toString()
typedArray.recycle()
}
}
override fun onDraw(canvas: Canvas?) {
// 在 TextView 的基础上绘制自定义内容
super.onDraw(canvas)
canvas?.let {
// 设置画笔的颜色、字体大小等属性
val paint = Paint()
paint.color = Color.RED
paint.textSize = 60f
// 绘制自定义内容
it.drawText(customText, 10f, 80f, paint)
}
}
}
```
在这段代码中,我们定义了一个自定义 TextView 类 `CustomTextView`,继承了系统原生的 TextView,并在其基础上增加了自定义属性 `customText` 和自定义绘制内容,具体实现如下:
- 在构造函数中,解析 XML 中我们定义的自定义属性 `customText` 的值,并赋值给自定义属性变量 `customText`;
- 在 `onDraw` 方法中,首先调用父类的 `onDraw` 方法,绘制原生的 TextView 内容;然后使用画笔设置颜色、字体大小等属性,绘制我们的自定义内容。
最后,我们需要在 XML 文件中定义自定义属性,并将 `TextView` 替换成 `CustomTextView`,示例如下:
```
<!-- 声明自定义属性 -->
<declare-styleable name="CustomTextView">
<attr name="customText" format="string" />
</declare-styleable>
<!-- 使用自定义 TextView ,并设置自定义属性 customText 的值 -->
<com.example.CustomTextView
android:id="@+id/custom_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="原生 TextView 的文本内容"
app:customText="自定义绘制的文本内容"
/>
```