java - 如何在android中为自定义视图创建setter和getter
问题描述
我正在构建一个扩展视图并为图像获取参数的自定义视图。到目前为止,我一直在实现从可绘制对象和服务器(通过字符串 URL)绘制图像。
class CustomView(context: Context, attrSet: AttributeSet) : View(context){
private var typedArray = context.obtainStyledAttributes(attrSet, R.styleable.CustomView)
private var viewColor = typedArray.getColor(R.styleable.CustomView_viewColor, Color.WHITE)
private var viewSize = typedArray.getDimensionPixelSize(R.styleable.CustomView_viewSize, 200)
private var rect = Rect(50, 50, this.left+viewSize, this.top+viewSize)
var viewImage = typedArray.getResourceId(R.styleable.CustomView_viewImage, -1)
var imageBitmap:Bitmap?=null
var imageString = typedArray.getString(R.styleable.CustomView_imageString)
val radius = 100f
var cx = 0f
var cy = 0f
private var paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var circlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var labelPaint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
paint.color = viewColor
circlePaint.color = Color.parseColor("#000000")
labelPaint.color = Color.parseColor("#000000")
typedArray.recycle()
try {
val iStream = URL(imageString)
imageBitmap = BitmapFactory.decodeResource(resources, viewImage) ?: BitmapFactory.decodeStream(iStream.openStream())
}catch (e:Exception){
Log.i("Image", "Kindly provide a valid image")
}
}
override fun onDraw(canvas: Canvas?) {
if(cx == 0f || cy == 0f){
cx = (width/2).toFloat()
cy = (height/2).toFloat()
}
canvas?.drawRect(rect, paint)
canvas?.drawCircle(cx, cy, radius, circlePaint)
if (imageBitmap != null){
canvas?.drawBitmap(imageBitmap!!, 50f, 100f, null)
}
}
}
我还希望能够在运行时在 xml 之外更改此值,例如在活动或片段中以使其动态化。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url =
"https://dyl80ryjxr1ke.cloudfront.net/external_assets/hero_examples/hair_beach_v1785392215/original.jpeg"
customView.imageString = url
}
}
解决方案
在 CustomView 类中,将 init 函数中的行设置为如下所示的设置函数:
class CustomView(context: Context, attrSet: AttributeSet) : View(context) {
//setups
init()
{
setupFunction(imageString)
}
fun setupFunction(url: String) {
paint.color = viewColor
circlePaint.color = Color.parseColor("#000000")
labelPaint.color = Color.parseColor("#000000")
typedArray.recycle()
try {
val iStream = URL(imageString)
imageBitmap = BitmapFactory.decodeResource(resources, viewImage)
?: BitmapFactory.decodeStream(iStream.openStream())
} catch (e: Exception) {
Log.i("Image", "Kindly provide a valid image")
}
}
onDraw()
}
现在 setupFunction() 可以在每次你想要这样的时候从你的 Fragment 或 Activity 调用:
customView.setupFunction(url)
并且视图将根据需要启动。
推荐阅读
- json - Items 对象应该具有相同的属性
- python - Tensorflow 示例在 colab 上运行良好,但在 jupyter lab 上运行时给出了 nan
- postman - 使用邮递员上传的文件在请求正文中显示未定义
- javascript - 我怎样才能反编译,编译的vue组件
- mongodb - mongo中的最小嵌套数组
- xml - 覆盖网络驱动器上的 xml 文件
- html - 基于 CSS/HTML 中的内容和容器的 3 行动态 div 高度
- jib - 如何在 Jib 创建的容器中配置标准路径
- angular - Angular 9 - 单例服务
- python-3.x - 循环遍历每一列