先寫一個你要的佈局文件作爲標題欄
head_title.xml
?xml version=”1.0” encoding=”utf-8”?>
LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”horizontal”>
ImageView
android:id=”@+id/bt_back”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/icon_return_back”/>
TextView
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”1”
android:layout_marginLeft=”20dp”
android:gravity=”center”
android:text=”標題欄”/>
Button
android:id=”@+id/bt_edit”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Edit”/>
再寫一個類繼承LinearLayout
構造方法 必須是public
(必須調用父類的super(context,attributes))
package com.example.dy.myapplication;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* Created by dy on 2015/4/15.
*/
public class DLinearLayout extends LinearLayout implements View.OnClickListener{
private ImageView bt_back ;
private Button bt_exit ;
public DLinearLayout(Context context,AttributeSet attributeSet){
// 不許聲明public
super(context,attributeSet); // 調用父類的構造方法 這個是必須的
View view = LayoutInflater.from(context).inflate(R.layout.head_title,this);
// 加載佈局文件
bt_back =(ImageView)view.findViewById(R.id.bt_back); // 得到控件
bt_exit = (Button) view.findViewById(R.id.bt_edit);
bt_back.setOnClickListener(this);
bt_exit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// 觸發事件
switch (v.getId()){
case R.id.bt_back:
((Activity) getContext()).finish();
break ;
case R.id.bt_edit:
Toast.makeText(getContext(),"this is Exit",Toast.LENGTH_SHORT).show();
break ;
}
}
}
佈局中調用這個就可以了:
RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent”
android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”>
com.example.dy.myapplication.DLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.dy.myapplication.DLinearLayout>