自定义组合控件的使用步骤:
- 编写布局文件
- 实现构造方法
- 初始化UI
- 提供对外的方法
- 在布局当中引用该控件
- activity中使用
布局文件
layout:lib_platform_layout.xml
attrs.xml中设置自定义属性:
<declare-styleable name="PublishPlatformLayout">
<attr name="lineVisible" format="boolean" />
</declare-styleable>
完整代码:
open class PublishPlatformLayout : LinearLayoutCompat {
private lateinit var binding: LibPlateformLayoutBinding
private var platformListener: OnPlatformListener? = null
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
if (attrs != null) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.PublishPlatformLayout)
val lineVisible = ta.getBoolean(R.styleable.PublishPlatformLayout_lineVisible, false)
ta.recycle()
}
binding = LibPlateformLayoutBinding.inflate(LayoutInflater.from(context), this, true)
}
fun initLayout(onPlatformListener: OnPlatformListener) {
platformListener = onPlatformListener
}
private fun buildPlatFormItemView(): View {
val itemBinding = ItemPublishPlatformBinding
.inflate(LayoutInflater.from(context), binding.gridLayout, false)
itemBinding.rlValid.visibility = View.GONE
// ....
return itemBinding.root
}
fun showPlatformAdapter(list: List<ThirdAuthApi.ThirdAuthInfo>?) {
binding.gridLayout.removeAllViews()
// 。。。。
if (!hasDouyin) {
binding.gridLayout.addView(buildPlatFormItemView(false, Constant.PLATFORM_DOUYIN, null))
}
}
interface OnPlatformListener {
fun onCheckedChange(isChecked: Boolean)
}
}