Cómo habilitar homeAsUp o llamar a setDisplayHomeAsUpEnabled () en la barra de herramientas independiente con appcompat v21


Estoy tratando de convertir mi aplicación para usar la biblioteca v21 AppCompat, así que comencé a usar Toolbar en lugar de ActionBar. En todas mis actividades regulares (que extienden ActionBarActivity) todo está bien. pero en mi SettingsActivity que extiende PreferenceActivity, y por lo tanto no puedo usar la llamada setSupportActionBar(actionbar) Necesito usar una barra de herramientas "independiente". La barra de herramientas se muestra, pero no puedo averiguar cómo podría agregar el botón" inicio / arriba " a la barra.

SettingsActivity.java:

public class SettingsActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        Toolbar actionbar = (Toolbar) findViewById(R.id.actionbar);
        if (null != actionbar) {

            // In every other activity that extends ActionBarActivity I simply use:
            // setSupportActionBar(actionbar);
            // final ActionBar supportActionBar = getSupportActionBar();
            // supportActionBar.setDisplayHomeAsUpEnabled(true);

            // but in PreferenceActivity you need to add a standalone toolbar:    
            actionbar.setTitle(R.string.title_activity_settings);
            actionbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SettingsActivity.this.finish();
                }
            });

            // Inflate a menu to be displayed in the toolbar
            actionbar.inflateMenu(R.menu.settings);
        }
    }
}

Layout/activity_settings.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              tools:context=".SettingsActivity"
              tools:menu="settings"
              tools:actionBarNavMode="standard"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <include
        layout="@layout/actionbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@android:id/list" />
</LinearLayout>

Layout/actionbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<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_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimaryDark"
    app:theme="@style/AppTheme"
    />

Menú/configuración.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.fletech.android.redalert.SettingsActivity" >
</menu>

Traté de agregar actionBarStyle y displayOptions a mi tema como se explica en Mostrar/botón atrás en android anidado PreferenceScreen?, pero en otros lugares la gente dijo que actionBarStyle no se usará cuando use Toolbar, y parecen tener razón.

Valores/temas.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimary</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="windowActionModeOverlay">true</item>

        <!-- Set AppCompat’s actionBarStyle -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="Widget.AppCompat.ActionBar">
        <item name="displayOptions">showHome|homeAsUp|showTitle</item>
    </style>
<resources>
Author: Community, 2014-11-04

7 answers

La solución de@Pedro Oliveira funcionó. Incluso pude encontrar el elemento de diseño que usa la biblioteca AppCompat (y por lo tanto ya está incluido en el apk). Además, también se refleja, por lo que funciona tanto para ltr, rtl locales:

actionbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

Y esto es todo junto, con la corrección de @VictorYakunin

public class SettingsActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        Toolbar actionbar = (Toolbar) findViewById(R.id.actionbar);
        if (null != actionbar) {
            actionbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

            actionbar.setTitle(R.string.title_activity_settings);
            actionbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    NavUtils.navigateUpFromSameTask(SettingsActivity.this);
                }
            });

            // Inflate a menu to be displayed in the toolbar
            actionbar.inflateMenu(R.menu.settings);
        }
    }
}
 56
Author: Gavriel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-14 21:07:50

Puedes usar ?homeAsUpIndicator en lugar de R.drawable.abc_ic_ab_back_mtrl_am_alpha:

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:navigationIcon="?homeAsUpIndicator"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:title="@string/title"
        />
 25
Author: ls.illarionov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 05:45:50

Camino de llegar tarde a la fiesta aquí, pero todavía voy a proporcionar mi 0.02$. lo hice de la siguiente manera para mostrar la marca de flecha hacia arriba en fragment usando AppCompactActivity

((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Y maneja el evento onClick dentro de tu actividad onOptionsItemSelected

 10
Author: war_Hero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-26 18:22:22

Si proporciona el nombre de la actividad principal en Manifest.xml y metadatos para admitir Android 4.0 y versiones anteriores, puede configurar el icono de navegación (toolbar.setNavigationIcon(R.drawable.ic_action_back);) y funcionará.

Manifiesto.ejemplo xml:

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ProductActivity"
        android:label="@string/title_activity_product"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>
 6
Author: Tomasz Mularczyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-22 14:42:00

Gracias por la solución, el único punto a añadir es que es mejor usar

NavUtils.navigateUpFromSameTask(SettingsActivity.this); 
 2
Author: Viktor Yakunin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-12 19:41:49

Define un background 9patch para tu barra de herramientas ;) es trabajo. Aquí está toolbar_background.9.png

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/toolbar_background">

    .....
 2
Author: Stéphane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-23 05:44:29

Pruebe el atributo XML android:navigationIcon o app:navigationIcon para API anteriores a 21.

 0
Author: Xingang Huang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 16:29:29