效果图

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

实现方案

方案概述

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

主要实现代码

  1. 组合view xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:gravity="center_vertical"
android:orientation="horizontal">

<ImageView
android:id="@+id/currentLocationLogoIv"
android:layout_width="11.4dp"
android:layout_height="14dp"
android:layout_marginRight="4dp"
android:src="@mipmap/location" />

<TextView
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="科技园" />
</LinearLayout>

<TextView
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="江苏省南京市" />

</LinearLayout>
  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文件
<resources>
<declare-styleable name="LocationViewWithAttrs">
<attr name="locationName" format="string" />
<attr name="locationDesc" format="string" />
</declare-styleable>
</resources>

调用方式

  1. xml设置
<com.cxyzy.customview.LocationViewWithAttrs
android:id="@+id/locationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:locationDesc="A市B区C路D号"
app:locationName="程序园中猿中心" />
  1. 通过开放方法设置
locationView.setData("程序园中猿中心", "A市B区C路D号")

备注

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

源代码

​https://gitee.com/cxyzy1/custom_view​