Android自定义控件之自定义组合控件(三)自定义控件之自定义组合控件(三)
前言:前言:
前两篇介绍了自定义控件的基础原理Android自定义控件基本原理详解(一)、Android自定义控件之自定义属性(二)。今天
重点介绍一下如何通过自定义组合控件来提高布局的复用,降低开发成本,以及维护成本。
使用自定义组合控件的好处?使用自定义组合控件的好处?
我们在项目开发中经常会遇见很多相似或者相同的布局,比如APP的标题栏,我们从三种方式实现标题栏来对比自定义组件带
来的好处,毕竟好的东西还是以提高开发效率,降低开发成本为导向的。
1.)第一种方式:)第一种方式:直接在每个xml布局中写相同的标题栏布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:lee="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:background="@color/green"
android:layout_height="45dp">
<Button
android:id="@+id/title_bar_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:background="@mipmap/titlebar_back_icon"
android:minHeight="45dp"
android:minWidth="45dp"
android:textSize="14sp" />
<TextView
android:id="@+id/title_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="登录"
android:singleLine="true"
android:textSize="17sp" />
<Button
android:id="@+id/title_bar_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="7dp"
android:text="提交"
android:textColor="@android:color/white"
android:background="@null"
android:minHeight="45dp"
android:minWidth="45dp"
android:textSize="14sp" />
</RelativeLayout>
</LinearLayout>
这种方式没有任何布局复用的概念,同时也让当前的布局变得臃肿难以维护,开发效率低下,而且这个还需要要求每个开发人
员必须细心否则有可能会做出参差不齐的标题栏,所以这种方式是最不推荐使用的。
2.)第二种方式:)第二种方式:使用include标签
首先定义标题栏布局