您当前的位置: 首页 > 

蓝不蓝编程

暂无认证

  • 0浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

安卓自定义view之组合view

蓝不蓝编程 发布时间:2019-12-19 14:49:09 ,浏览量:0

效果图

实现方案 方案概述

通过在xml布局文件中组合控件,通过自定义view类加载xml文件,让外部通过xml属性或者方法来设置数据.

主要实现代码
  1. 组合view xml文件


    

        

        
    

    


  1. 自定义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 }
    }
}
  1. styles文件

    
        
        
    

调用方式
  1. xml设置

  1. 通过开放方法设置
locationView.setData("程序园中猿中心", "A市B区C路D号")
备注

如果不需要支持xml设置,那就不需要上面的styles文件以及自定义view文件中对于style的处理方法initTypeValue.

源代码

https://gitee.com/cxyzy1/custom_view

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0745s