商城项目实战 | 2.1 Android 仿京东商城——自定义 Toolbar (一)

来源:互联网 发布:创维32e300e数据 编辑:程序博客网 时间:2024/05/21 07:11

本文为菜鸟窝作者刘婷的连载。”商城项目实战”系列来聊聊仿”京东淘宝的购物商城”如何实现。

现在很多的 APP 里面都有自己的自定义风格,特别是京东商城中自定义的头部布局——自定义的 Toolbar 效果非常不错,看上去很美观,其效果图如下。

想要定义出这样的效果并不是很难,主要是要对控件的属性熟悉以及对控件的熟练使用,下面就先简单了解下 Toolbar 的基本属性以及简单使用。

什么是 Toolbar

1. Toolbar 的解释

Toolbar 是 android 5.0 引入的一个新控件,可以理解为是 ActionBar 的升级版,大大扩展了 Actionbar,使用更灵活,不像 actionbar 那么固定,Toolbar 更像是一般的View元素,可以被放置在 view 树体系的任意位置,可以应用动画,可以跟着 scrollView 滚动,可以与布局中的其他 view 交互。

2. Toolbar 的基本属性

####1. xml style属性:

colorPrimaryDark:状态栏的颜色(可用来实现沉浸效果)。
colorPrimary: Toolbar 的背景颜色 (xml中用android:background=”?attr/colorPrimary”指定)。
android:textColorPrimary:Toolbar中文字的颜色,设置后Menu Item 的字体颜色也会跟随。
colorAccent:EditText 正在输入时,RadioButton 选中时的颜色。

2. xml 属性:

app:title=”App Title”:Toolbar 中的 App Title。
app:subtitle=”Sub Title” :Toobar 中的小标题。
app:navigationIcon=”?attr/homeAsUpIndicator” : 导航图标,比如返回图标(与 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。

toolbar=(Toolbar)findViewById(R.id.home_toolbar_main);

3.声明定义之后还需要配置一下,设置 toolbar。

setSupportActionBar(toolbar);

4.添加标题

 setTitle("首页");

5.最后只要设置 Application 的 Style —— AppTheme 和 Activity 的 Style —— AppTheme.NoActionBar 就可以了,因为已经有了 Toolbar 了,替代了 ActionBar,所以在 Activity 的 Theme 中需要设置为 windowActionBar 为 false。

 <!-- 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 的基本使用就介绍完了,下一节中将会开始介绍如何自定义属于自己的 Toolbar。

1 0