Android自定義控制項之自定義組合控制項(三)

来源:http://www.cnblogs.com/whoislcj/archive/2016/07/29/5714760.html
-Advertisement-
Play Games

前言: 前兩篇介紹了自定義控制項的基礎原理Android自定義控制項之基本原理(一)、自定義屬性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標簽

 首先定義標題欄佈局

    <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: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: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:background="@null"
            android:minHeight="45dp"
            android:minWidth="45dp"
            android:textSize="14sp" />
    </RelativeLayout>

然後在需要的地方通過include標簽實現引用

<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">

    <include layout="@layout/view_title_bar" />

</LinearLayout>

通過上面的佈局代碼,我們可以使用上面這種方式確實實現了佈局的復用,而且也避免了開發人員開發出參差不齊標題欄的問題,但是同時也引入了新的問題,比如更加降低了開發效率,加大了開發成本,問題就在我們該如何為每個佈局文件定義標題欄?只有通過代碼的方式來設置標題問題,左右按鈕等其他的屬性,導致佈局屬性和Activity代碼耦合性比較高,所以這種方式也不是推薦的方式。

3.)第三種方式:通過自定義組合控制項

    這裡先不具體介紹如何實現一個自定義組合控制項,這裡先介紹一下自定義組合控制項帶來的好處。

  • 提高佈局文件開發效率
  • 降低佈局文件維護成本
  • 降低佈局文件和Activity代碼耦合性
  • 容易擴展
  • 簡單易用

 如何實現一個自定義組合控制項

1.)先定義一個佈局文件

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <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="@null"
        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: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:background="@null"
        android:minHeight="45dp"
        android:minWidth="45dp"
        android:textSize="14sp" />

</merge>

註意:這裡為何要使用merge標簽,自定義組合控制項時會繼承RelativeLayout、LinearLayout等控制項,這樣導致佈局的層級無形中增加了一層,如下是對比:

未使用merge標簽

 

使用merge標簽

2.)定義自定義屬性

比如標題文字、標題欄左邊按鈕圖標等。

 <declare-styleable name="CustomTitleBar">
        <attr name="title_background_color" format="reference|integer" />
        <attr name="left_button_visible" format="boolean" />
        <attr name="right_button_visible" format="boolean" />
        <attr name="title_text" format="string" />
        <attr name="title_text_color" format="color" />
        <attr name="title_text_drawable" format="reference|integer" />
        <attr name="right_button_text" format="string" />
        <attr name="right_button_text_color" format="color" />
        <attr name="right_button_drawable" format="reference|integer" />
        <attr name="left_button_text" format="string" />
        <attr name="left_button_text_color" format="color" />
        <attr name="left_button_drawable" format="reference|integer" />
    </declare-styleable>

3.)自定義一個View根據需求繼承不同的ViewGroup子類,比如:RelativeLayout、LinearLayout等,我們這裡繼承RelativeLayout。

public class CustomTitleBar extends RelativeLayout {
    private Button titleBarLeftBtn;
    private Button titleBarRightBtn;
    private TextView titleBarTitle;

    public CustomTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.custom_title_bar, this, true);
        titleBarLeftBtn = (Button) findViewById(R.id.title_bar_left);
        titleBarRightBtn = (Button) findViewById(R.id.title_bar_right);
        titleBarTitle = (TextView) findViewById(R.id.title_bar_title);

        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomTitleBar);
        if (attributes != null) {
            //處理titleBar背景色
            int titleBarBackGround = attributes.getResourceId(R.styleable.CustomTitleBar_title_background_color, Color.GREEN);
            setBackgroundResource(titleBarBackGround);
            //先處理左邊按鈕
            //獲取是否要顯示左邊按鈕
            boolean leftButtonVisible = attributes.getBoolean(R.styleable.CustomTitleBar_left_button_visible, true);
            if (leftButtonVisible) {
                titleBarLeftBtn.setVisibility(View.VISIBLE);
            } else {
                titleBarLeftBtn.setVisibility(View.INVISIBLE);
            }
            //設置左邊按鈕的文字
            String leftButtonText = attributes.getString(R.styleable.CustomTitleBar_left_button_text);
            if (!TextUtils.isEmpty(leftButtonText)) {
                titleBarLeftBtn.setText(leftButtonText);
                //設置左邊按鈕文字顏色
                int leftButtonTextColor = attributes.getColor(R.styleable.CustomTitleBar_left_button_text_color, Color.WHITE);
                titleBarLeftBtn.setTextColor(leftButtonTextColor);
            } else {
                //設置左邊圖片icon 這裡是二選一 要麼只能是文字 要麼只能是圖片
                int leftButtonDrawable = attributes.getResourceId(R.styleable.CustomTitleBar_left_button_drawable, R.mipmap.titlebar_back_icon);
                if (leftButtonDrawable != -1) {
                    titleBarLeftBtn.setBackgroundResource(leftButtonDrawable);
                }
            }

            //處理標題
            //先獲取標題是否要顯示圖片icon
            int titleTextDrawable = attributes.getResourceId(R.styleable.CustomTitleBar_title_text_drawable, -1);
            if (titleTextDrawable != -1) {
                titleBarTitle.setBackgroundResource(titleTextDrawable);
            } else {
                //如果不是圖片標題 則獲取文字標題
                String titleText = attributes.getString(R.styleable.CustomTitleBar_title_text);
                if (!TextUtils.isEmpty(titleText)) {
                    titleBarTitle.setText(titleText);
                }
                //獲取標題顯示顏色
                int titleTextColor = attributes.getColor(R.styleable.CustomTitleBar_title_text_color, Color.WHITE);
                titleBarTitle.setTextColor(titleTextColor);
            }

            //先處理右邊按鈕
            //獲取是否要顯示右邊按鈕
            boolean rightButtonVisible = attributes.getBoolean(R.styleable.CustomTitleBar_right_button_visible, true);
            if (rightButtonVisible) {
                titleBarRightBtn.setVisibility(View.VISIBLE);
            } else {
                titleBarRightBtn.setVisibility(View.INVISIBLE);
            }
            //設置右邊按鈕的文字
            String rightButtonText = attributes.getString(R.styleable.CustomTitleBar_right_button_text);
            if (!TextUtils.isEmpty(rightButtonText)) {
                titleBarRightBtn.setText(rightButtonText);
                //設置右邊按鈕文字顏色
                int rightButtonTextColor = attributes.getColor(R.styleable.CustomTitleBar_right_button_text_color, Color.WHITE);
                titleBarRightBtn.setTextColor(rightButtonTextColor);
            } else {
                //設置右邊圖片icon 這裡是二選一 要麼只能是文字 要麼只能是圖片
                int rightButtonDrawable = attributes.getResourceId(R.styleable.CustomTitleBar_right_button_drawable, -1);
                if (rightButtonDrawable != -1) {
                    titleBarRightBtn.setBackgroundResource(rightButtonDrawable);
                }
            }
            attributes.recycle();
        }
    }

    public void setTitleClickListener(OnClickListener onClickListener) {
        if (onClickListener != null) {
            titleBarLeftBtn.setOnClickListener(onClickListener);
            titleBarRightBtn.setOnClickListener(onClickListener);
        }
    }

    public Button getTitleBarLeftBtn() {
        return titleBarLeftBtn;
    }

    public Button getTitleBarRightBtn() {
        return titleBarRightBtn;
    }

    public TextView getTitleBarTitle() {
        return titleBarTitle;
    }
}

4.)在不同的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">

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:right_button_drawable="@mipmap/titlebar_add_icon"
        lee:title_background_color="@color/green"
        lee:title_text="標題1" />

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:right_button_visible="false"
        lee:title_background_color="@color/green"
        lee:title_text="標題2" />

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:left_button_text="左邊"
        lee:right_button_text="右邊"
        lee:title_background_color="@color/red"
        lee:title_text="標題3" />

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:left_button_text="左邊"
        lee:right_button_drawable="@mipmap/titlebar_add_icon"
        lee:title_background_color="@color/red"
        lee:title_text="標題4" />

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:left_button_text="左邊"
        lee:left_button_text_color="@color/red"
        lee:right_button_drawable="@mipmap/titlebar_add_icon"
        lee:title_background_color="@color/blue"
        lee:title_text="標題5" />

    <com.whoislcj.views.CustomTitleBar
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        lee:left_button_text="左邊"
        lee:left_button_text_color="@color/red"
        lee:right_button_drawable="@mipmap/titlebar_add_icon"
        lee:title_background_color="@color/blue"
        lee:title_text="標題6"
        lee:title_text_color="@color/black" />

</LinearLayout>

顯示效果

總結:

    通過本篇文章我們得知,通過自定義組合控制項確實能夠提高開發效率,降低維護成本,但是也需要UI設計風格保持高度一致,不然的話只能呵呵噠了!所以想要做好一個app需要一個有共識的團隊才行。本篇介紹到此為止,下一篇要更新什麼我還沒有想好!有可能是自定義控制項的事件回調,也有可能自定義ViewGroup實現流式佈局。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 視頻錄製,從總體上講,界面是用xib畫的,進入到錄製界面,上面有四個按鈕,分別是退出、前後置攝像頭切換、閃光燈、播放按鈕,這四個按鈕在一個view上,同過調整view的約束,可以改變view的位置。下麵是一個進度條,這是一個自定義的view。最下麵有兩個button,一個是錄製按鈕,另一個是調取相冊 ...
  • 下載git安裝 ->https://git-scm.com/downloads 新建git目錄 在目錄下右鍵選擇Git Bash Here 創建一個身份標識git config --global user.name 你的github用戶名 git config --global user.email ...
  • 有這樣一種場景,當你在手機APP上輸入你的信息,會自動跳出一個彈窗,表示某任務已執行。最簡單的一個例子就是當你輸入手機號,點擊獲取驗證碼的時候,就會跳出一個對話框,說“驗證碼已發送到手機,請註意查收”,這些都是如何實現的。 ...
  • 使用ListView需要為其添加適配器: 適配器有兩種:1.ArrayAdapter --用於單獨文字顯示 2.SimpleAdapter --用於文字和圖片顯示 這裡主要記錄SimpleAdapter: 先看SimpleAdapter的構造函數: SimpleAdapter(context,dat ...
  • 使用lowercaseString,uppercaseString -(void)test{ NSString * str = @"person"; NSString * str1 = [str lowercaseString]; NSString * str2 = [str uppercaseSt ...
  • 上一次分享了應用加固的評測後,很多人想看看漏洞掃描相關的對比數據。其實在選擇市面上這些移動安全類的產品時,經常為各種複雜的數據而感到疑惑,不知道怎麼來評判各自的性能以及價格,從而選擇出一款性價比高的安全產品。那麼這一篇文章我就先來比較一下市場中現有產品的服務和收費情況。 ...
  • (偷懶,寫簡略點) 自定義一個Request類 public class MyRequest extends Request<JSONObject> 存儲上一次連接的sessionid @Override protected Response<JSONObject> parseNetworkResp ...
  • Images.xcassets概述功能方便用戶管理圖像資源。圖片獲取方式Images.xcassets中的圖片資源只能通過imageNamed:方法載入,通過NSBundle的pathForResource:ofType:無法獲得圖片路徑。因此,Images.xcassets只適合存放系統常用的,占... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...