1 @JvmOverloads
@JvmOverloads注解在Kotlin中的作用就是:暴露多个重载方法;
class CustomVideoView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
init {
println("自定义View")
}
}
在自定义View时,如果在Java中,那么需要写3个重载方法,例如
public class CustomVideoView(Context context){
super(context);
}
public class CustomVideoView(Context context,AttributeSet set){
super(context,set);
}
。。。
2 自定义View的实现
虽然例子简单,但是流程搞明白了,难的问题自然就不再难了
class CustomVideoView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
private var _context : Context = context
//展示的背景url
private var src:String?
private var backgroundColor:Int?
private lateinit var iv_mine:ImageView
private lateinit var container:ConstraintLayout
init {
println("自定义View 初始化操作")
//获取自定义属性
var obtainStyledAttributes =
_context.obtainStyledAttributes(attrs, R.styleable.CustomVideoView)
src = obtainStyledAttributes.getString(R.styleable.CustomVideoView_src)
backgroundColor = obtainStyledAttributes.getColor(R.styleable.CustomVideoView_videoview_background,Color.BLUE)
initView()
}
private fun initView() {
//动态加载布局
var inflate = View.inflate(_context, R.layout.layout_video_view, this)
iv_mine = inflate.findViewById(R.id.iv_mine)
container = inflate.findViewById(R.id.container)
backgroundColor?.let { container.setBackgroundColor(it) }
}
fun setUrl(url:String){
this.src = url
Glide.with(_context).load(this.src).into(iv_mine)
}
fun setBackGroundColor(color:Int){
this.backgroundColor = color
this.backgroundColor?.let {
container.setBackgroundColor(it)
}
}
}
2.1 初始化操作
init中可以执行初始化的操作,例如画笔的创建、自定义属性的获取、动态加载View XML等
2.2 自定义属性
(1)在res/values文件夹下,创建自定义属性xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--声明给哪个自定义的组件自定义属性-->
<declare-styleable name="CustomVideoView">
<!--组件自定义属性-->
<attr name="src" format="string"/>
<attr name="videoview_background" format="color|reference"/>
</declare-styleable>
</resources>
(2)在init中,通过obtainStyledAttributes获取全部的自定义属性,并分别拿到这些自定义属性
(3)通过拿到的自定义属性,来设置到布局中
2.3 使用
<com.example.kotlinlearn.vire.CustomVideoView
android:id="@+id/cus_video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:videoview_background="@color/red"/>
在XML文件中,使用自定义View,自定义属性通过app:xxx设置
2.4 动态设置自定义View属性
可以设置一些set方法,在代码中动态设置View的属性,对应的UI完成操作