android自定义组合view,安卓自定义view之组合view

效果图

be5676335665

image

实现方案

方案概述

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

主要实现代码

组合view xml文件

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="16dp"

android:gravity="center_vertical"

android:orientation="horizontal">

android:id="@+id/currentLocationLogoIv"

android:layout_width="11.4dp"

android:layout_height="14dp"

android:layout_marginRight="4dp"

android:src="@mipmap/location" />

android:id="@+id/locationNameTv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginRight="9dp"

android:textColor="#ff333333"

android:textSize="16sp"

tools:text="科技园" />

android:id="@+id/locationAddressTv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="16dp"

android:textColor="#999999"

android:textSize="12sp"

tools:text="江苏省南京市" />

自定义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设置

android:id="@+id/locationView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:locationDesc="A市B区C路D号"

app:locationName="程序园中猿中心" />

通过开放方法设置

locationView.setData("程序园中猿中心", "A市B区C路D号")

备注

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

源代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值