本文以 Sencha Touch 2.2 為基礎,示範如何繼承 Ext.Toolbar,做出一條可切換選中態的底部導航欄,效果等同 TabPanel 內建的 TabBar,但外觀與行為都能完全自訂。
核心概念是:把 Toolbar 固定在底部,讓子按鈕平均伸展,並自行維護「目前選中按鈕」這個狀態,透過增刪 CSS class 來呈現高亮。
Ext.define('ux.TabBar', {
alternateClassName: 'tabBar',
extend: 'Ext.Toolbar',
xtype: 'tabBar',
config: {
docked: 'bottom',
cls: 'navToolbar',
layout: {
align: 'stretch'
},
defaults: {
flex: 1
},
selectButton: null // 目前被選中的按鈕
},
initialize: function () {
var me = this;
me.callParent();
// 監聽按鈕點擊事件
me.on({
delegate: '> button',
scope: me,
tap: 'onButtonTap'
});
},
// 切換選中按鈕樣式
updateSelectButton: function (newItem, oldItem) {
if (oldItem) {
oldItem.removeCls('x-tabBar-pressing');
}
if (newItem) {
newItem.addCls('x-tabBar-pressing');
}
},
onButtonTap: function (button) {
this.setSelectButton(button);
},
/**
* @private
* 加入子項時自動觸發,用來決定初始選中項
*/
onItemAdd: function (item, index) {
if (!this.getSelectButton() && item.getInitialConfig('selected')) {
this.setSelectButton(item);
}
this.callParent(arguments);
}
});
.navToolbar {
padding: 0;
}
.navToolbar .x-button {
border: 0;
margin: 0;
border-right: 1px solid #585B5B;
border-radius: 0;
padding: 0;
}
.navToolbar .x-button .x-button-label {
font-weight: normal;
color: #fff;
font-size: 0.6em;
}
.navToolbar .x-tabBar-pressing {
background-image: none;
background-color: #0f517e;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%,
color-stop(0%, #0a3351), color-stop(10%, #0c4267),
color-stop(65%, #0f517e), color-stop(100%, #0f5280));
background-image: -webkit-linear-gradient(top, #0a3351, #0c4267 10%, #0f517e 65%, #0f5280);
background-image: -moz-linear-gradient(top, #0a3351, #0c4267 10%, #0f517e 65%, #0f5280);
background-image: -o-linear-gradient(top, #0a3351, #0c4267 10%, #0f517e 65%, #0f5280);
background-image: linear-gradient(top, #0a3351, #0c4267 10%, #0f517e 65%, #0f5280);
}
直接繼承 ux.TabBar 並填入按鈕清單即可。若要指定初始選中項,只需在該按鈕上加 selected: true;由於元件只會採用第一個被標記的項目,因此最多只有一個按鈕會預先高亮。
Ext.define('app.view.MyBar', {
alternateClassName: 'myBar',
extend: 'ux.TabBar',
xtype: 'myBar',
config: {
items: [
{ xtype: 'button', text: '問卷調查', selected: true },
{ xtype: 'button', text: '我的積分' },
{ xtype: 'button', text: '開獎大廳' },
{ xtype: 'button', text: '幸運號碼' },
{ xtype: 'button', text: '更多' }
]
}
});
完成後的效果如下圖所示:

這個做法的優點在於把「選中態」抽象成元件自己的設定屬性,之後不管是放在 TabPanel 的底部,還是獨立用於頁面切換,都能重複使用同一份邏輯。