Android组合控件
组合控件,顾名思义,多个控件组合成一个控件使用。比如,我们想要这样一个ImageView,图片的底部覆盖一个浮层,浮层上面显示一行文字,这个控件我们可以用TextView覆盖在ImageView之上实现,我们把这个控件命名为“CoverImageView”吧。
怎样组合
既然是组合,那么就需要一个容器把这些分散的控件装在一起,这个容器就是ViewGroup,如:LinearLayout、RelativeLayout等,所以组合控件都是继承于一个ViewGroup的。
组装的方式有两种:
xml文件里定义好控件效果,然后通过LayoutInflater布局到ViewGroup里面;
直接在ViewGroup里面通过代码添加子控件,实现效果。
第一种方式能够比较直观的看到组合效果,但是由于需要解析xml,所以性能上稍微差点;第二种并不能直观的看到效果,但是性能稍好。对于新手来说,可以先用第一种方式实现,等到对组合控件的实现比较熟悉后可以使用第二种方式实现。
基本效果实现
能实现覆盖效果的ViewGroup有RelativeLayout、FrameLayout,我们以FrameLayout为例。
xml布局如下:
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="@drawable/demo"/>
android:layout_width="match_parent"