本文為菜鳥窩作者劉婷的連載。"商城項(xiàng)目實(shí)戰(zhàn)"系列來聊聊仿"京東淘寶的購物商城"如何實(shí)現(xiàn)。
現(xiàn)在很多的 APP 里面都有自己的自定義風(fēng)格耗拓,特別是京東商城中自定義的頭部布局——自定義的 Toolbar 效果非常不錯,看上去很美觀荧恍,其效果圖如下。
想要定義出這樣的效果并不是很難屯吊,主要是要對控件的屬性熟悉以及對控件的熟練使用送巡,下面就先簡單了解下 Toolbar 的基本屬性以及簡單使用。
什么是 Toolbar
1. Toolbar 的解釋
Toolbar 是 android 5.0 引入的一個新控件雌芽,可以理解為是 ActionBar 的升級版授艰,大大擴(kuò)展了 Actionbar辨嗽,使用更靈活世落,不像 actionbar 那么固定,Toolbar 更像是一般的View元素,可以被放置在 view 樹體系的任意位置屉佳,可以應(yīng)用動畫谷朝,可以跟著 scrollView 滾動,可以與布局中的其他 view 交互武花。
2. Toolbar 的基本屬性####
1. xml style屬性:
colorPrimaryDark:狀態(tài)欄的顏色(可用來實(shí)現(xiàn)沉浸效果)圆凰。
colorPrimary: Toolbar 的背景顏色 (xml中用android:background=”?attr/colorPrimary”指定)。
android:textColorPrimary:Toolbar中文字的顏色体箕,設(shè)置后Menu Item 的字體顏色也會跟隨专钉。
colorAccent:EditText 正在輸入時,RadioButton 選中時的顏色累铅。
2. xml 屬性:
app:title=”App Title”:Toolbar 中的 App Title跃须。
app:subtitle=”Sub Title” :Toobar 中的小標(biāo)題。
app:navigationIcon=”?attr/homeAsUpIndicator” : 導(dǎo)航圖標(biāo)娃兽,比如返回圖標(biāo)(與 Logo 不同)菇民。
Toolbar 的簡單使用
1.首先在布局 layout 文件中寫入引用代碼。
<android.support.v7.widget.Toolbar
android:id="@+id/home_toolbar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:navigationIcon="?attr/homeAsUpIndicator"
</android.support.v7.widget.Toolbar>
2.然后在 Activity 中聲明定義該控件投储,注意 Activity 必須是繼承于 AppCompatActivity第练。
xml
toolbar=(Toolbar)findViewById(R.id.home_toolbar_main);
3.聲明定義之后還需要配置一下,設(shè)置 toolbar玛荞。
xml
setSupportActionBar(toolbar);
4.添加標(biāo)題娇掏。
xml
setTitle("首頁");
5.最后只要設(shè)置 Application 的 Style —— AppTheme 和 Activity 的 Style —— AppTheme.NoActionBar 就可以了,因?yàn)橐呀?jīng)有了 Toolbar 了冲泥,替代了 ActionBar驹碍,所以在 Activity 的 Theme 中需要設(shè)置為 windowActionBar 為 false。
xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimary</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- activity theme. -->
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
6.效果圖凡恍。
到這里 Toolbar 的基本使用就介紹完了志秃,下一節(jié)中將會開始介紹如何自定義屬于自己的 Toolbar。
(菜鳥窩嚼酝,程序員的黃埔軍校浮还,轉(zhuǎn)載請注明出處)
添加菜鳥窩運(yùn)營微信:yrioyou,備注【菜鳥商城】闽巩,入群學(xué)習(xí)
關(guān)注菜鳥窩官網(wǎng)钧舌,免費(fèi)領(lǐng)取“140套開源項(xiàng)目”