将图像添加到导航抽屉工具栏并设置自定义背景

时间:2016-11-29 15:31:11

标签: android

我需要将图像添加到导航抽屉工具栏/操作栏。显示在菜单图标右侧和活动标题左侧的小圆形图像。 我还需要将工具栏/操作栏的背景更改为我自己的自定义图像。

这是否可行,如果是,我如何在我的Android应用程序中完成此操作?

1 个答案:

答案 0 :(得分:1)

对于任何困惑的人,OP都在使用Android Studio的NavigationView Activity,而不是空活动。

汉堡菜单图标右侧的图像和标题左侧的图像如下所示:

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

if (getSupportActionBar() != null) {
    getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title

    // Setting background using a drawable
    Drawable toolbarBackground = getResources().getDrawable(R.drawable.ic_menu_gallery);
    getSupportActionBar().setBackgroundDrawable(toolbarBackground);
}

现在我们已经隐藏了标题,我们将把我们自己的标题TextView和图标ImageView添加到工具栏中,这将是您的app_bar_main.xml布局(res / layout)。

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/my_custom_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_menu_share"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My Custom Title"
            android:id="@+id/my_custom_title"
            android:layout_toRightOf="@id/menu_icon"/>
    </RelativeLayout>
</android.support.v7.widget.Toolbar>

现在,您可以引用my_custom_title和my_custom_icon并添加您想要的任何标题和图标(您可能需要修改布局,我只是指向正确的方向)。

TextView myCustomTitleTV = (TextView) findViewById(R.id.my_custom_title);
myCustomTitleTV.setText("My Custom Title");