拼凑自定义控件
引用布局的技巧确实解决了重复编写布局代码的问题, 但还有优化的空间.
比如说标题栏中的返回按钮,其实不管是在哪一个活动中,这个按钮的功能都是相同的,即销毁当前Activity。
这种情况最好是使用自定义控件的方式来解决。  
1 新建 TitleLayout 继承自 LinearLayout,让它成为我们自定义的标题栏控件
代码如下所示:
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        Button titleBack = (Button) findViewById(R.id.title_back);
        Button titleEdit = (Button) findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                // 销毁
                ((Activity) getContext()).finish();
            }
        });
        titleEdit.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                // 吐司
                Toast.makeText(getContext(), "你点击了右侧按钮", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
tiele布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_banner" >
    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="@drawable/bt_menu_show"
        android:text="Back"
        android:textColor="#fff" />
    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="#fff"
        android:textSize="24sp" />
    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="@drawable/ico_letter"
        android:text="Edit"
        android:textColor="#fff" />
</LinearLayout>
2 在Activity的布局中添加这个自定义控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.yassblog.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </com.yassblog.TitleLayout>
</LinearLayout>