具有扩展工具栏的Android材质

时间:2014-10-22 21:10:26

标签: 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>

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

1 个答案:

答案 0 :(得分:6)

好的,您的活动会延长ActionBarActivity,因此您还必须确保此活动的主题是Theme.AppCompat.NoActionBarTheme.AppCompat.Light.NoActionBar的子项。如果您没有使用Theme.AppCompat变体,那么您也可以在主题中添加以下行:

<item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item> 

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

<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" />

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

    Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mToolbar);

最后一部分就是所有魔法发生的地方,因为你正在说&#34; Android,拿这个工具栏小部件并使用完全你将如何使用SupportActionBar&#34;。这意味着如果你想设置标题/副标题,你需要做的就是调用:

    getSupportActionBar().setTitle("Toolbar Title");
    getSupportActionBar().setSubtitle("Toolbar Subtitle");

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

直接回答您的问题:

  

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

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

  

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

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