900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > android自定义组合view 安卓自定义view之组合view

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

时间:2020-03-19 04:06:59

相关推荐

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

效果图

image

实现方案

方案概述

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

主要实现代码

组合view xml文件

xmlns:tools="/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.

源代码

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。