Adding backbutton on top of child element of Toolbar

两盒软妹~` 提交于 2019-12-10 21:35:56

问题


I have the following Layout file. How can I add a back button (arrow) on top of (or overlayed on, like a z-index) the Imageview child of Toolbar in my below layout?

<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">


<Toolbar
    android:layout_width="fill_parent"
    android:layout_height="600dp"
    android:id="@+id/toolbar"
    android:background="#313B45"
    android:weightSum="1"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/headerimage"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:layout_gravity="left|top"
            android:layout_weight="1" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="New Text"
            android:id="@+id/textView"
            android:scaleType="fitXY"
            android:layout_gravity="left|top"
            android:layout_weight="1" />

    </LinearLayout>
</Toolbar>


回答1:


You have to set home button of toolbar enable by the following line getSupportActionBar().setDisplayHomeAsUpEnabled(true); and to override the action on back button you have to override onOptionItemSelected method. look for the given code it will help you... :D

        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

To override the OnOptionItemSelected use the following code

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        finish();
        break;

    default:
        break;
    }
        return super.onOptionsItemSelected(item);
    }


来源:https://stackoverflow.com/questions/29448116/adding-backbutton-on-top-of-child-element-of-toolbar

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