效果图
通过在xml布局文件中组合控件,通过自定义view类加载xml文件,让外部通过xml属性或者方法来设置数据.
主要实现代码- 组合view xml文件
- 自定义view类
class LocationViewWithAttrs(
context: Context,
attrs: AttributeSet?
) : LinearLayout(context, attrs) {
var name: String? = null
var address: String? = null
init {
initTypeValue(context, attrs)
initView(context)
}
private fun initTypeValue(
context: Context,
attrs: AttributeSet?
) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.LocationViewWithAttrs)
name = typedArray.getString(R.styleable.LocationViewWithAttrs_locationName)
address = typedArray.getString(R.styleable.LocationViewWithAttrs_locationDesc)
typedArray.recycle()
}
private fun initView(context: Context) {
LayoutInflater.from(context).inflate(R.layout.view_location, this, true)
setData(name,address)
}
fun setData(name: String?, address: String?) {
name?.let { locationNameTv.text = it }
address?.let { locationAddressTv.text = it }
}
}
- styles文件
调用方式
- xml设置
- 通过开放方法设置
locationView.setData("程序园中猿中心", "A市B区C路D号")
备注
如果不需要支持xml设置,那就不需要上面的styles文件以及自定义view文件中对于style的处理方法initTypeValue.
源代码https://gitee.com/cxyzy1/custom_view