Android之Toolbar

2 篇文章 0 订阅
1 篇文章 0 订阅

一、为什么要使用Toolbar

从 Android 3.0(API 级别 11)开始,所有使用默认主题的 Activity 均使用 ActionBar 作为应用栏。

不过,经过不同 Android 版本的演化,应用栏功能已逐渐添加到原生 ActionBar 中。

因此,原生 ActionBar 的行为会随设备使用的 Android 系统的版本而发生变化。

相比之下,最新功能已添加到支持库版本的 Toolbar 中,并且这些功能可以在任何能够使用该支持库的设备上使用。

因此,您应使用支持库的 Toolbar 类来实现 Activity 的应用栏。

使用支持库的工具栏有助于确保您的应用在最大范围的设备上保持一致的行为。


二、如何使用Toolbar

(1)确保你的Activity继承了AppCompatActivity

(2)在应用清单中,将 <application> 元素设置为使用 appcompat 的其中一个 NoActionBar 主题。使用这些主题中的一个可以防止应用使用原生 ActionBar 类提供应用栏。

例如:

<application
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"
    />
(3) 向 Activity 的布局添加一个 Toolbar

<android.support.v7.widget.Toolbar
   android:id="@+id/my_toolbar"
   android:layout_width="match_parent"
   android:layout_height="?attr/actionBarSize"
   android:background="?attr/colorPrimary"
   android:elevation="4dp"
   android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
   app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
(4) 在 Activity 的 onCreate() 方法中,调用 Activity 的 setSupportActionBar()  方法,然后传递 Activity 的工具栏。该方法会将工具栏设置为 Activity 的应用栏。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    }
现在你的的应用现在具有一个基本操作栏。默认情况下,操作栏只包含应用的名称和一个溢出菜单。

注意!Toolbar是作为一个UI组件存在的,在你的布局中不要让Toolbar覆盖了你的组件,你的组件应当在Toolbar的下方

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startActivity2"
        <!--如果不设置这个属性,Button就会被Toolbar覆盖而无法显示-->
        android:layout_below="@id/my_toolbar"
        android:text="StartActivity"
        android:id="@+id/button"/>

</RelativeLayout>


 





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值