android toolbar: how to have a toolbar with image in the background and menu items on top

女生的网名这么多〃 提交于 2019-12-05 01:00:29

If you insist on using an ImageView over using the .setBackground(...) function.

You can try using a RelativeLayout with the Toolbar overlaying an ImageView like this:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageViewplaces"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/YOUR_IMAGE" />

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar_actionbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

    </android.support.v7.widget.Toolbar>


</RelativeLayout>

Instead of adding an element with the image to the toolbar add the image as background of the toolbar, code below.

<android.support.v7.widget.Toolbar     
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/actionBar"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:contentInsetEnd="0dp"
    app:contentInsetStart="0dp"
    android:background="@drawable/puri"
    android:minHeight="200dp">

    </android.support.v7.widget.Toolbar>

If you want to change it in java code, you can call toolbar.setBackground(ContextCompat.getDrawable(yourcontext, R.drawable/puri);

A more proper solution would be to use an AppBarLayout:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbarlayout"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:src="@drawable/bg"
        android:scaleType="centerCrop"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </RelativeLayout>
</android.support.design.widget.AppBarLayout>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!