class CustomViewGroup: LinearLayout {
lateinit var title: TextView
lateinit var operation: TextView
constructor(context: Context): this(context, null)
constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
//因为我们引入的布局文件根布局是merge,而我们的CustomViewGroup又是继承LinearLayout,所以我们在这里设置几个属性
this.orientation = HORIZONTAL
this.gravity = Gravity.CENTER_VERTICAL
this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorAccent))
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
//加载你的组合布局文件到这个自定义的CustomViewGroup内
val inflate = LayoutInflater.from(context).inflate(R.layout.view_custom_viewgroup, this)
//利用findViewById找到你布局文件中的控件
val ivBack: ImageView = inflate.findViewById(R.id.iv_back)
//如返回键无特殊操作,可以直接finish(),如有其它操作可自定义其它操作方法
ivBack.setOnClickListener {(context as Activity).finish()}
title = inflate.findViewById(R.id.tv_title)
operation = inflate.findViewById(R.id.tv_operation)
/
/获取可配置的属性,设置给控件
val attr = context.obtainStyledAttributes(attrs, R.styleable.CustomViewGroup)
title.text = attr.getString(R.styleable.CustomViewGroup_title)
operation.text = attr.getString(R.styleable.CustomViewGroup_operation)
//用完要回收
attr.recycle()
}
/ 可以对外提供设置text方法 /
fun setTitle(s: String){
title.text = s
}
fun setOperation(s: String){
operation.text = s
}
//设置对右文本的点击监听
fun setOnOperationClickListener(listener: OnOperationClickListener){
operation.setOnClickListener {
listener.onClick()
}
}
}
interface OnOperationClickListener{
fun onClick()
}
使用
xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- 就是你啊 --><com.limeng.thecreator.view.CustomViewGroup
android:id="@+id/cvg_title"
br/><com.limeng.thecreator.view.CustomViewGroup
android:id="@+id/cvg_title"
android:layout_height="wrap_content"
app:title="我是标题"
app:operation="筛选"/>
<Buttonandroid:id="@+id/bt_change_title"
br/>android:id="@+id/bt_change_title"
android:layout_height="wrap_content"
android:text="改变标题"/>
<Buttonandroid:id="@+id/bt_change_operation"
br/>android:id="@+id/bt_change_operation"
android:layout_height="wrap_content"
android:text="改变右文本"/>
</LinearLayout>
在activity中
尾声
一转眼时间真的过的飞快。我们各奔东西,也各自踏上了自己的旅途,但是即使多年不见,也因为这份情谊我们依旧如从前那般“亲密”。不忘初心方得始终。加油吧,程序员们,在我看来35岁,40岁从来不是危机,只要永远不要忘记自己为何踏上征程!
为了让更多在学习中或者最近要准备面试的朋友们看到这篇文章,希望你们能多多评论,点赞+转发!
再次感谢所有给我提供过题目的朋友们,感谢一路有你!