【Android自定義View實戰】之自定義項目通用的標題欄CustomTitleBar

轉載請注明出處:http://blog.csdn.net/linglongxin24/article/details/52948152 【DylanAndroid的csdn博客】


在Android開發中,一般來說項目中都會用到一個通用風格的標題欄,比如說左邊返回按鈕,中間顯示標題,最后邊可能會有一個保存按鈕。如下圖


這里寫圖片描述

那么我們是不是每次在新建一個布局的時候都要去用一個線性布局去加載三個控件,特別麻煩。我們自定義之后,一個控件就好了,下面就來看一下如何來打造通用的自定義標題欄。

1.首先在layout文件夾下定義一個pub_titlebar.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="#654454"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/left_button"
        android:layout_width="48dp"
        android:layout_height="match_parent"
        android:textColor="#FFFFFF"
        android:background="@mipmap/arrow_left"
       />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:textColor="#000000"
        android:text="標題"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/right_button"
        android:layout_width="48dp"
        android:layout_height="match_parent"
        android:background="@null"
        android:gravity="center"
        android:textColor="#000000"
        android:text="保存"
        android:textSize="16sp" />
</LinearLayout>

2.在res的values文件夾下新建一個attrs.xml

這些可以設置的變量可以在布局文件中動態去設置,特別方便

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomTitleBar">
        <attr name="title_background" format="color"/>
        <attr name="left_button_image" format="reference|integer"/>
        <attr name="left_button_text" format="string"/>
        <attr name="left_button_textColor" format="color"/>
        <attr name="left_button_textSize" format="dimension"/>
        <attr name="show_left_button" format="boolean"/>
        <attr name="title_text" format="string"/>
        <attr name="title_textColor" format="color"/>
        <attr name="title_textSize" format="dimension"/>
        <attr name="right_button_image" format="reference|integer"/>
        <attr name="right_button_text" format="string"/>
        <attr name="right_button_textColor" format="color"/>
        <attr name="right_button_textSize" format="dimension"/>
        <attr name="show_right_button" format="boolean"/>
    </declare-styleable>
</resources>

3.自定義CustomTitleBar繼承自LinearLayout


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Android自定義標題欄
 * Created by yuandl on 2016-10-27.
 */

public class CustomTitleBar extends LinearLayout {
    /**
     * 標題欄的根布局
     */
    private LinearLayout ll;
    /**
     * 標題欄的左邊按返回按鈕
     */
    private TextView left_button;
    /**
     * 標題欄的右邊按保存按鈕
     */
    private TextView right_button;
    /**
     * 標題欄的中間的文字
     */
    private TextView title;
    /**
     * 標題欄的背景顏色
     */
    private int title_background_color;
    /**
     * 標題欄的顯示的標題文字
     */
    private String title_text;
    /**
     * 標題欄的顯示的標題文字顏色
     */
    private int title_textColor;
    /**
     * 標題欄的顯示的標題文字大小
     */
    private int title_textSize;


    /**
     * 返回按鈕的資源圖片
     */
    private int left_button_imageId;
    /**
     * 返回按鈕上顯示的文字
     */
    private String left_button_text;
    /**
     * 返回按鈕上顯示的文字顏色
     */
    private int left_button_textColor;
    /**
     * 返回按鈕上顯示的文字大小
     */
    private int left_button_textSize;
    /**
     * 是否顯示返回按鈕
     */
    private boolean show_left_button;


    /**
     * 右邊保存按鈕的資源圖片
     */
    private int right_button_imageId;
    /**
     * 右邊保存按鈕的文字
     */
    private String right_button_text;
    /**
     * 右邊保存按鈕的文字顏色
     */
    private int right_button_textColor;
    /**
     * 右邊保存按鈕的文字大小
     */
    private int right_button_textSize;
    /**
     * 是否顯示右邊保存按鈕
     */
    private boolean show_right_button;

    /**
     * 標題的點擊事件
     */
    private TitleOnClickListener titleOnClickListener;

    public CustomTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        /**加載布局文件*/
        LayoutInflater.from(context).inflate(R.layout.pub_titlebar, this, true);
        ll = (LinearLayout) findViewById(R.id.ll);
        left_button = (TextView) findViewById(R.id.left_button);
        right_button = (TextView) findViewById(R.id.right_button);
        title = (TextView) findViewById(R.id.title);

        /**獲取屬性值*/
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTitleBar);
        /**標題相關*/
        title_background_color = typedArray.getColor(R.styleable.CustomTitleBar_title_background, Color.WHITE);
        title_text = typedArray.getString(R.styleable.CustomTitleBar_title_text);
        title_textColor = typedArray.getColor(R.styleable.CustomTitleBar_title_textColor, Color.BLACK);
        title_textSize = typedArray.getColor(R.styleable.CustomTitleBar_title_textSize, 22);
        /**返回按鈕相關*/
        left_button_imageId = typedArray.getResourceId(R.styleable.CustomTitleBar_left_button_image, R.mipmap.arrow_left);
        left_button_text = typedArray.getString(R.styleable.CustomTitleBar_left_button_text);
        left_button_textColor = typedArray.getColor(R.styleable.CustomTitleBar_left_button_textColor, Color.WHITE);
        left_button_textSize = typedArray.getColor(R.styleable.CustomTitleBar_left_button_textSize, 20);
        show_left_button = typedArray.getBoolean(R.styleable.CustomTitleBar_show_left_button, true);
        /**右邊保存按鈕相關*/
        right_button_imageId = typedArray.getResourceId(R.styleable.CustomTitleBar_right_button_image, 0);
        right_button_text = typedArray.getString(R.styleable.CustomTitleBar_right_button_text);
        right_button_textColor = typedArray.getColor(R.styleable.CustomTitleBar_right_button_textColor, Color.WHITE);
        right_button_textSize = typedArray.getColor(R.styleable.CustomTitleBar_right_button_textSize, 20);
        show_right_button = typedArray.getBoolean(R.styleable.CustomTitleBar_show_right_button, true);
        /**設置值*/

        setTitle_background_color(title_background_color);
        setTitle_text(title_text);
        setTitle_textSize(title_textSize);
        setTitle_textColor(title_textColor);
        setShow_left_button(show_left_button);
        setShow_right_button(show_right_button);
        if (!TextUtils.isEmpty(left_button_text)) {//返回按鈕顯示為文字
            setLeft_button_text(left_button_text);
            setLeft_button_textColor(left_button_textColor);
            setLeft_button_textSize(left_button_textSize);
        } else {
            setLeft_button_imageId(left_button_imageId);
        }

        if (!TextUtils.isEmpty(right_button_text)) {//返回按鈕顯示為文字
            setRight_button_text(right_button_text);
            setRight_button_textColor(right_button_textColor);
            setRight_button_textSize(right_button_textSize);
        } else {
            setRight_button_imageId(right_button_imageId);
        }
        left_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (titleOnClickListener != null) {
                    titleOnClickListener.onLeftClick();
                }
            }
        });
        right_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (titleOnClickListener != null) {
                    titleOnClickListener.onRightClick();
                }
            }
        });
    }

    /**
     * 獲取左邊的返回按鈕
     *
     * @return Button
     */
    public TextView getLeft_button() {
        return left_button;
    }

    /**
     * 獲取標題欄的跟布局
     *
     * @return LinearLayout
     */
    public LinearLayout getLl() {
        return ll;
    }

    /**
     * 獲取標題欄標題TextView
     *
     * @return TextView
     */
    public TextView getTitle() {
        return title;
    }

    /**
     * 獲取右邊的保存按鈕
     *
     * @return Button
     */
    public TextView getRight_button() {
        return right_button;
    }

    /**
     * 設置返回按鈕的資源圖片id
     *
     * @param left_button_imageId 資源圖片id
     */
    public void setLeft_button_imageId(int left_button_imageId) {
        left_button.setBackgroundResource(left_button_imageId);
    }

    /**
     * 設置返回按鈕的文字
     *
     * @param left_button_text
     */
    public void setLeft_button_text(String left_button_text) {
        left_button.setText(left_button_text);
    }

    /**
     * 設置返回按鈕的文字顏色
     *
     * @param left_button_textColor
     */
    public void setLeft_button_textColor(int left_button_textColor) {
        left_button.setTextColor(left_button_textColor);
    }

    /**
     * 設置返回按鈕的文字大小
     *
     * @param left_button_textSize
     */
    public void setLeft_button_textSize(int left_button_textSize) {
        left_button.setTextSize(left_button_textSize);
    }

    /**
     * 設置是否顯示返回按鈕
     *
     * @param show_left_button
     */
    public void setShow_left_button(boolean show_left_button) {
        left_button.setVisibility(show_left_button ? VISIBLE : INVISIBLE);
    }


    /**
     * 設置右邊保存按鈕的資源圖片
     *
     * @param right_button_imageId
     */
    public void setRight_button_imageId(int right_button_imageId) {
        right_button.setBackgroundResource(right_button_imageId);
    }

    /**
     * 設置右邊的保存按鈕的文字
     *
     * @param right_button_text
     */
    public void setRight_button_text(String right_button_text) {
        right_button.setText(right_button_text);
    }

    /**
     * 設置右邊保存按鈕的文字顏色
     *
     * @param right_button_textColor
     */
    public void setRight_button_textColor(int right_button_textColor) {
        right_button.setTextColor(right_button_textColor);
    }

    /**
     * 設置右邊保存按鈕的文字大小
     *
     * @param right_button_textSize
     */
    public void setRight_button_textSize(int right_button_textSize) {
        right_button.setTextSize(right_button_textSize);
    }

    /**
     * 設置是顯示右邊保存按鈕
     *
     * @param show_right_button
     */
    public void setShow_right_button(boolean show_right_button) {
        right_button.setVisibility(show_right_button ? VISIBLE : INVISIBLE);
    }


    /**
     * 設置標題背景的顏色
     *
     * @param title_background_color
     */
    public void setTitle_background_color(int title_background_color) {
        ll.setBackgroundColor(title_background_color);
    }

    /**
     * 設置標題的文字
     *
     * @param title_text
     */
    public void setTitle_text(String title_text) {
        title.setText(title_text);
    }

    /**
     * 設置標題的文字顏色
     *
     * @param title_textColor
     */
    public void setTitle_textColor(int title_textColor) {
        title.setTextColor(title_textColor);
    }

    /**
     * 設置標題的文字大小
     *
     * @param title_textSize
     */
    public void setTitle_textSize(int title_textSize) {
        title.setTextSize(title_textSize);
    }


    /**
     * 設置標題的點擊監聽
     *
     * @param titleOnClickListener
     */
    public void setOnTitleClickListener(TitleOnClickListener titleOnClickListener) {
        this.titleOnClickListener = titleOnClickListener;
    }

    /**
     * 監聽標題點擊接口
     */
    public interface TitleOnClickListener {
        /**
         * 返回按鈕的點擊事件
         */
        void onLeftClick();

        /**
         * 保存按鈕的點擊事件
         */
        void onRightClick();

    }
}

4.用法

  • 在布局文件中的引用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="cn.bluemobi.dylan.MainActivity">

   <cn.bluemobi.dylan.CustomTitleBar
       android:id="@+id/ct"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:title_text="標題一"></cn.bluemobi.dylan.CustomTitleBar>

   <cn.bluemobi.dylan.CustomTitleBar
       android:layout_marginTop="10dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:show_left_button="false"
       app:title_text="標題二"></cn.bluemobi.dylan.CustomTitleBar>

   <cn.bluemobi.dylan.CustomTitleBar
       android:layout_marginTop="10dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:show_right_button="false"
       app:title_text="標題三"></cn.bluemobi.dylan.CustomTitleBar>

   <cn.bluemobi.dylan.CustomTitleBar
       android:layout_marginTop="10dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:show_left_button="false"
       app:show_right_button="false"
       app:title_text="標題四"></cn.bluemobi.dylan.CustomTitleBar>
</LinearLayout>

  • 在Activity中的用法

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomTitleBar customTitleBar = (CustomTitleBar) findViewById(R.id.ct);
        customTitleBar.setOnTitleClickListener(new CustomTitleBar.TitleOnClickListener() {
            @Override
            public void onLeftClick() {
                Toast.makeText(MainActivity.this, "點擊了左邊的返回按鈕", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRightClick() {
                Toast.makeText(MainActivity.this, "點擊了右邊的保存按鈕", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

5.效果圖

這里寫圖片描述

6 GitHub地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,797評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,179評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,628評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,642評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,444評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,948評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,040評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,185評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,717評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,794評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,418評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,414評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,750評論 2 370

推薦閱讀更多精彩內容