編輯:關於 Android 開發
做 Android 開發時,經常需要一個自訂的頂部導覽列。本篇就以一個帶有標題、左按鈕與右按鈕的 TopBar 為例,完整走一遍自訂控制項的開發流程。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="TopBar"> <attr name="titleText" format="string"></attr> <attr name="titleTextSize" format="dimension"></attr> <attr name="titleTextColor" format="reference|color"></attr> <attr name="leftButtonText" format="string"></attr> <attr name="leftButtonTextSize" format="dimension"></attr> <attr name="leftButtonBackground" format="reference|color"></attr> <attr name="rightButtonText" format="string"></attr> <attr name="rightButtonTextSize" format="dimension"></attr> <attr name="rightButtonBackground" format="reference|color"></attr> </declare-styleable> </resources>
為了簡單起見,這裡讓 TopBar 繼承 RelativeLayout:
package com.sphere.topbar; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class TopBar extends RelativeLayout { private String titleText; private float titleTextSize; private int titleTextColor; private String leftButtonText; private float leftButtonTextSize; private Drawable leftButtonBackground; private String rightButtonText; private float rightButtonTextSize; private Drawable rightButtonBackground; private TextView titleTextView; private Button leftButton; private Button rightButton; private LayoutParams titleLayoutParams; private LayoutParams leftBtnLayoutParams; private LayoutParams rightBtnLayoutParams; private TopBarOnClickListener listener; // 定義點擊響應事件回調接口 interface TopBarOnClickListener{ public abstract void onLeftButtonClicked(); public abstract void onRightButtonClicked(); } @SuppressLint("NewApi") public TopBar(Context context, AttributeSet attrs) { super(context, attrs); // 得到xml文件自定的屬性集合 TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.TopBar); // 得到title的各個屬性 titleText = ta.getString(R.styleable.TopBar_titleText); titleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, 0); titleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0); // 得到left button的各個屬性 leftButtonText = ta.getString(R.styleable.TopBar_leftButtonText); leftButtonTextSize = ta.getDimension(R.styleable.TopBar_leftButtonTextSize, 0); leftButtonBackground = ta.getDrawable(R.styleable.TopBar_leftButtonBackground); // 得到right button的各個屬性 rightButtonText = ta.getString(R.styleable.TopBar_rightButtonText); rightButtonTextSize = ta.getDimension(R.styleable.TopBar_rightButtonTextSize, 0); rightButtonBackground = ta.getDrawable(R.styleable.TopBar_rightButtonBackground); // initial inner basic component leftButton = new Button(context); rightButton = new Button(context); titleTextView = new TextView(context); // 設置屬性 titleTextView.setText(titleText); titleTextView.setTextSize(titleTextSize); titleTextView.setTextColor(titleTextColor); titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); titleTextView.setLayoutParams(titleLayoutParams); leftButton.setText(leftButtonText); leftButton.setTextSize(leftButtonTextSize); leftButton.setBackground(leftButtonBackground); leftBtnLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); leftBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE); leftButton.setLayoutParams(leftBtnLayoutParams); rightButton.setText(rightButtonText); rightButton.setTextSize(rightButtonTextSize); rightButton.setBackground(rightButtonBackground); rightBtnLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); rightBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE); rightButton.setLayoutParams(rightBtnLayoutParams); // 添加到View中 addView(titleTextView); addView(leftButton); addView(rightButton); //addView(View child, ViewGroup.LayoutParams params); ta.recycle(); leftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onLeftButtonClicked(); } }); rightButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onRightButtonClicked(); } }); } /** * 類的實例調用此方法 * 以匿名內部類的形式現實接口中的方法 * @param listener */ public void setTopBarOnClickListener(TopBarOnClickListener listener){ this.listener = listener; } /** * 設置導航背景顏色 * @param color */ public void setTopBarBackgroundColor(int color){ this.setBackgroundColor(color); } /** * 設置按鈕是否可見 * @param show */ public void setLeftButtonVisible(boolean show){ leftButton.setVisibility(show ? View.VISIBLE : View.GONE); } public void setRightButtonVisible(boolean show){ rightButton.setVisibility(show ? View.VISIBLE : View.GONE); } }
這裡有幾個要點:
必須提供帶有 Context context, AttributeSet attrs 兩個參數的建構子。
從 XML 中讀取各個屬性,並設定給對應的內部控制項。
別忘了呼叫 addView(),把內部包含的控制項加入這個 View。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:myTopBar="https://schemas.android.com/apk/res-auto" 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.sphere.topbar.TopBar android:id="@+id/topbar" android:layout_width="match_parent" android:layout_height="48dp" myTopBar:titleText="自定義標題" myTopBar:titleTextColor="#000" myTopBar:titleTextSize="10sp" myTopBar:leftButtonText="Back" myTopBar:leftButtonBackground="#ff00ff" myTopBar:leftButtonTextSize="10sp" myTopBar:rightButtonText="More" myTopBar:rightButtonBackground="#00ff00" myTopBar:rightButtonTextSize="10sp" /> </RelativeLayout>
這裡要注意:必須加上命名空間 xmlns:myTopBar="https://schemas.android.com/apk/res-auto"。如果你用的是 ADT 開發環境,則要寫成 xmlns:myTopBar="https://schemas.android.com/apk/res/com.sphere.topbar"。
雖然 myTopBar 這個名字可以隨便取,但不能使用 android,否則會與系統衝突;在 ADT 中引用時,需要在 res 後面接上完整的套件名稱。引用自訂屬性時,以 myTopBar:屬性名 開頭。
package com.sphere.topbar; import android.graphics.Color; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private TopBar mTopBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTopBar = (TopBar)findViewById(R.id.topbar); mTopBar.setBackgroundColor(Color.parseColor("#46B4CD")); mTopBar.setTopBarOnClickListener(new TopBar.TopBarOnClickListener() { @Override public void onLeftButtonClicked() { Toast.makeText(MainActivity.this,"Back",Toast.LENGTH_SHORT).show(); } @Override public void onRightButtonClicked() { Toast.makeText(MainActivity.this, "More", Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
這裡我們拿到自訂控制項的實例,呼叫 setTopBarOnClickListener(TopBarOnClickListener listener) 方法,就能為左右按鈕掛上點擊事件監聽器。
效果圖如下:

HandlerThread 打造可控生命週期的異步後台線程
HandlerThread 打造可控生命週期的異步後台線程 使用 HandlerThread 的幾大優點: 1、能輕鬆打造一個後台異步線程,需要時丟一個任務給它即可,運用
Android 三維旋轉動畫實作與封裝:支援 X、Y、Z 三軸旋轉
本文介紹如何在 Android 中實作 3D(立體)旋轉動畫,並把它封裝成一個可重複使用的自訂 Animation 類別。以下是我實作出來的成果: 一、立體旋轉的三種
Greenplum 正式開源!MPP 資料倉庫的架構與核心特色一次看懂
Greenplum 是什麼 Greenplum Database(GPDB)是一套無共享(shared-nothing)架構的 MPP 大規模並行處理資料庫,主要處
Android 開發避坑清單:20 條實戰中踩過的陷阱
Android 開發避坑清單 有些問題只有在真實項目裡撞過一次才會記住。下面這些條目按性質分了類:資源與編譯、生命周期與界面、記憶體與數據、多進程、以及工具鏈。每一條背後