在工具栏的子元素顶部添加后退按钮

时间:2015-04-04 15:24:55

标签: android android-layout back-button android-toolbar

我有以下布局文件。如何在我的下方布局中在工具栏的Imageview子项上添加一个后退按钮(箭头)(或覆盖在z-index上)?

<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 个答案:

答案 0 :(得分:4)

您必须通过以下行设置工具栏启用的主页按钮 getSupportActionBar()。setDisplayHomeAsUpEnabled(true); 并覆盖后退按钮上的操作,您必须覆盖onOptionItemSelected方法。寻找给定的代码它会帮助你......:D

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

要覆盖OnOptionItemSelected,请使用以下代码

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

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