Cómo obtener la barra de herramientas de fragmento?


Tengo ActionBarActivity con NavigationDrawer y uso support_v7 Toolbar como barra de acción. En uno de mis fragmentos barra de herramientas tiene vista personalizada. En otros fragmentos Toolbar debe mostrar el título.

¿Cómo obtener Toolbar instancia para personalizar a partir de fragmentos? Puedo obtener ActionBar con getActivity().getActionBar(), pero si llamo a setTitle() para esta instancia ActionBar no hace nada.

UPD:

En mi caso

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle();

(como dijo MrEngineer13) no funciona en la creación del primer fragmento porque lo llamo desde onHiddenChanged(). Ahora agrego más a onCreateView () y funciona bien.

Author: mmBs, 2014-11-18

7 answers

Primero necesitas lanzar tu actividad de getActivity() a AppCompatActivity. He aquí un ejemplo:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

La razón por la que tienes que lanzarlo es porque getActivity() devuelve un FragmentActivity y necesitas un AppCompatActivity

 157
Author: MrEngineer13,
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-07-02 12:49:00

En caso de que los fragmentos deban tener una vista personalizada de la barra de herramientas, puede implementar la barra de herramientas para cada fragmento por separado.

Añadir barra de herramientas a fragment_layout:

<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="?attr/colorPrimaryDark"/>

Encuéntralo en el fragmento:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        //set toolbar appearance
        toolbar.setBackground(R.color.material_blue_grey_800);

        //for crate home button
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

El oyente de menú se puede crear de dos maneras: reemplazar onOptionsItemSelected en su fragmento:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
        case android.R.id.home:
            getActivity().onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

O establecer listener para toolbar cuando lo cree en onCreateView ():

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                return false;
            }
        });
 68
Author: Flinbor,
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-07-14 10:51:11

Tiene dos opciones para obtener la barra de herramientas en fragment

El primero

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

Y el segundo

Toolbar toolbar = ((MainActivity) getActivity()).mToolbar;
 37
Author: Bhargav Thanki,
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-13 06:14:14
toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
 7
Author: Danial,
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-06-22 11:04:56

Tal vez tenga que probar getActivity().getSupportActionBar().setTitle() si está utilizando support_v7.

 1
Author: Wang,
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-11-18 16:05:02

From your Fragment: (get Toolbar from fragment?)

// get toolbar
((MainAcivity)this.getActivity()).getToolbar();  // getToolbar will be method in Activity that returns Toolbar!!  don't use getSupportActionBar for getting toolbar!!
// get action bar
this.getActivity().getSupportActionBar();

Esto es muy útil cuando está utilizando spinner en la barra de herramientas y llama a las vistas spinner o personalizadas en la barra de herramientas desde un fragmento!

De su Actividad:

// get toolbar
this.getToolbar();
// get Action Bar
this.getSupportActionBar();
 1
Author: LOG_TAG,
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-07-17 08:59:55

Puedes crear un método para esto en tu clase de Actividad:

public void setToolbarTitle(String title) {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(title);
}

Y puedes usar así:

setToolbarTitle("Hello World");
 0
Author: Mete,
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-07-27 06:14:44