多控件组合复用

多控件组合复用:多个零散的控件需要在多个地方复用,而且长得都差不多——>封装成一个整体

①创建⼀个layout.xml资源⽂件(使用已有控件完成自己需要的布局)(用一个容器把需要复用的控件摆放好)
②引用某一个控件使⽤<include layout=”@layout/layout_user_input”>引⼊布局资源

1
2
3
4
5
6
<!--注意引入的时候需要重写layout_width和layout_height-->
<include
layout = "@layout/layout_user_input"
android:layout_width = "0dp"
android:layout_height = "0dp"
/>

xml:
布局方便,
只能实现布局、不能灵活配置


用一个类来关联xml文件,灵活地对xml文件中的内容进行配置

使用类来关联这个layout布局文件:

  1. xml完成布局
  2. 代码实现逻辑 (用一个类来管理视图View/ViewGroup)
1
2
3
4
5
6
7
8
9
10
11
//方法一
class UserInputView(context: Context,attrs:AttributeSet?) :LinearLayout(context,attrs){}

//方法二
/**使用代码创建一个控件时 调用这个构造方法*/
constructor(context:Context):super(context){}
/*在xml中添加一个控件 并设置对应属性 就调用这个构造方法*/
constructor(context: Context, attrs: AttributeSet?):super(context,attrs){}
/*在xml中添加一个控件 并且设置了style样式的就会调用这个构造方法*/
constructor(context: Context, attrs: AttributeSet?, style:lnt):super(context, attrs,style){}

1
2
3
4
5
6
init{  
//init方法
//当一个对象被创建时 1.构造函数 2.init方法
//创建一个对象又想做额外的事情
//在init方法中实现View和xml中布局视图关联
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class UserInputView(context: Context,attrs:AttributeSet?) :LinearLayout(context,attrs){
//找到控件 外部不能直接访问
private var titleTextView:TextView
private var inputEditText: EditText
init {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.layout_user_input,null,false)
//创建布局参数 view在FrameLayout中如何显示
val lp = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
//将解析出来的View添加到当前容器中 显示出来
addView(view,lp)

//获取对应控件 解析出View里面所有需要配置的控件
titleTextView = view.findViewById(R.id.titleTextView)
inputEditText = view.findViewById(R.id.inputEditText)
}
//暴露给外部 使用这些方法配置信息
fun setTitle(title:String){
titleTextView.text = title
}
fun setPlaceholder(text:String){
inputEditText.hint = text
}
}



//使用绑定后
class UserInputView(context: Context,attrs:AttributeSet?) :LinearLayout(context,attrs){
//使用的时候再去解析 懒加载
private val binding:LayoutUserInputBinding by lazy {
LayoutUserInputBinding.inflate(LayoutInflater.from(context))
}

init {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.layout_user_input,null,false)

//2.设置布局参数 view在FrameLayout中如何显示
val lp = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)

//3.添加到当前 View 上
//将解析出来的View添加到当前容器中 显示出来
addView(binding.root,lp)
}


//暴露给外部 使用这些方法配置信息
fun setTitle(title:String){
binding.titleTextView.text = title
}
fun setPlaceholder(text:String){
binding.inputEditText.hint = text
}
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信