具有扩展工具栏的Android材质

Fra*_*ola 4 android material-design android-toolbar

我正在测试材料设计,我正在使用扩展工具栏开发应用程序.我的应用程序非常简单:主要活动扩展ActionBarActivity,我的布局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WeatherActivity"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/my_toolbar"
        android:layout_height="128dp"
        popupTheme="@style/ActionBarPopupThemeOverlay"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:text="@string/location_placeholder"
        android:textAlignment="viewStart"
        android:layout_gravity="start"
        />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

现在我想将标题显示为当前位置.我注意到的第一件事是在我的Android模拟器(API 18)中,标题似乎不符合关于左边距底边距的材料指南,它出现在左侧并垂直输入工具栏内.我应该使用工具栏标题(toolbar.setTitle)还是其他什么?其次,如果我想创建更复杂的东西,如标题和简短的描述(如布局结构中的材料指南所示),我的布局应该是什么?谢谢您的支持!

MrE*_*r13 7

确定您的活动延伸,ActionBarActivity因此您还必须确保此活动的主题是其中之一Theme.AppCompat.NoActionBarTheme.AppCompat.Light.NoActionBar.如果您没有使用Theme.AppCompat变体,那么您也可以在主题中添加以下行:

<item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item> 
Run Code Online (Sandbox Code Playgroud)

然后,您需要做的就是将工具栏添加到您的布局(它看起来像您已经拥有):

<android.support.v7.widget.Toolbar
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_height="128dp"
    popupTheme="@style/ActionBarPopupThemeOverlay"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中通过setSupportActionBar以下方式将工具栏设置为您的ActionBar :

    Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mToolbar);
Run Code Online (Sandbox Code Playgroud)

最后一部分是所有魔术发生的地方,因为你说"Android,使用这个工具栏小部件并使用它完全如何使用SupportActionBar".这意味着如果你想设置标题/副标题,你需要做的就是调用:

    getSupportActionBar().setTitle("Toolbar Title");
    getSupportActionBar().setSubtitle("Toolbar Subtitle");
Run Code Online (Sandbox Code Playgroud)

这也意味着您可以使用相同的回调在工具栏上创建菜单.

直接回答您的问题:

我应该使用工具栏标题(toolbar.setTitle)还是其他什么?

你实际上可以使用,toolbar.setTitle()getSupportActionBar().setTitle()

其次,如果我想创建更复杂的东西,如标题和简短的描述(如布局结构中的材料指南所示),我的布局应该是什么?

工具栏支持标题和字幕,因此您应该进行设置.我会查看文档,看看所有工具栏支持的内容.作为一般规则,如果Actionbar可以执行此操作,则工具栏可以.如果您有超出工具栏支持的疯狂要求,那么请记住工具栏只是一个奇特的ViewGroup,因此您可以像添加LinearLayout一样轻松添加窗口小部件/视图.