简介
自定义组合控件就是多个控件组合起来 成为一个新的控件,其主要用于解决多次重复地使用同一类型的布局。比如我们应用的顶部标题栏及弹出 的固定样式的 Dialog,这些都是常用的,所以把它们所需要的控件组合起来重新定义成一个新的控件。
使用
首先,我们定义组合控件的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#FFFF00">
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="返回" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_weight="4"
android:text="标题栏" />
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:text="设置" />
</LinearLayout>
接下来编写Java代码。因为我们的组合控件 整体布局是LinearLayout,所以组合控件要继承LinearLayout。
public class CombinationView extends LinearLayout {
public CombinationView(Context context) {
super(context);
initView(context);
}
public CombinationView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public CombinationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
public void initView(Context context) {
LayoutInflater.from(context).inflate(R.layout.combination_view, this, true); //加载布局
}
}
布局中使用:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.echo.myview.CombinationView
android:layout_width="match_parent"
android:layout_height="wrap_content"></com.echo.myview.CombinationView>
</LinearLayout>
效果图:
添加自定义属性
在value文件夹中新建资源文件:
<resources>
<declare-styleable name="combination">
<attr name="title" format="string"></attr>
</declare-styleable>
</resources>
在CombinationView的构造函数中获取设置的自定义属性:
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.combination);
title = typedArray.getString(R.styleable.combination_title);
使用该组件时可以加入属性,combinationAttr可以替代成任意名称:
<com.echo.myview.CombinationView
xmlns:combinationAttr = "http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
combinationAttr:title = "Combination"></com.echo.myview.CombinationView>
效果: