How to implements hamburger icon in Drawer toggle

911 views Asked by At

I read this post but if I implements getActionBar.setIcon(drawer) method it is not exactly that I want. Following the instructions, the result is a simple icon in ActionBar.

This is my case. I have this:

enter image description here

And this in a seconds Activitys:

enter image description here

I want hamburger icon as Gmail app.

enter image description here

And this:

enter image description here

This is my code in main.java. It's a standard code.

public class Main extends Activity{

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        //Muestra el menu el lugar de < en el Toggle
        mDrawerToggle.setDrawerIndicatorEnabled(true);

        //Habilita la opción de mostrar el menu deslizando el dedo de izquierda a derecha
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        Log.d("Drawer", "Main. onBackPressed");

    }

    //Fragment
    TodasLasInstalacionesFragment todasLasInstalacionesFragment = null;
    //Navigation Drawer start
    public static DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    public static ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private String[] actionBarTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter; 

    ActionBarImplementation actionBar;
    final Context context = this;
    Activity activity = this;
    private DataBaseHelper myDbHelper;
    private Traductor traductor = new Traductor();
    private String alertaTitulo, alertaTexto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

            // Update the action bar title with the TypefaceSpan instance
        getActionBar().setTitle(mTitle);

        //actionBar = new ActionBarImplementation(this, this, R.string.app_name, OPCION_MENU);
        mTitle = mDrawerTitle = getTitle();

        //Añadimos el tipo de fuente
        SpannableString actionBarTitle = new SpannableString(mTitle);
        actionBarTitle.setSpan(new TypefaceSpan(this, "OpenSans-Semibold.ttf"), 0, actionBarTitle.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        //load ActionBar Titles
        actionBarTitles = getResources().getStringArray(R.array.actionbar_titles);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        //Drawer Layout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);

        //Drawer list
        mDrawerList = (ListView) findViewById(R.id.main_list_slidermenu);

        //Drawer header image
        View header=getLayoutInflater().inflate(R.layout.drawer_header, null);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Avisos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));

        //Establecemos el header
        mDrawerList.addHeaderView(header);

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);


        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {

                //Para el tipo de letra
                SpannableString actionBarTitle = new SpannableString(mTitle);
                TypefaceSpan tfs = new TypefaceSpan(context, "OpenSans-Semibold.ttf");  
                actionBarTitle.setSpan(tfs, 0, actionBarTitle.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                getActionBar().setTitle(actionBarTitle);
                //getActionBar().setTitle(mTitle);Antes de lo del tipo de letra

                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {

                //Para el tipo de letra
                SpannableString actionBarTitle = new SpannableString(mDrawerTitle);
                TypefaceSpan tfs = new TypefaceSpan(context, "OpenSans-Semibold.ttf");  
                actionBarTitle.setSpan(tfs, 0, actionBarTitle.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                getActionBar().setTitle(actionBarTitle);

                //getActionBar().setTitle(mDrawerTitle);Antes de lo del tipo de letra

                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);



        if (savedInstanceState == null) {
            // on first time display view for first nav item
            //Ejecuta el case 1 la primera vez que se inicia la aplicacion
            displayView(1);
        }               

    }




    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.general_activity_instalaciones_en_lista_actionbar_menu, menu);
        getMenuInflater().inflate(R.menu.menu_general_fragments, menu);
        menu.findItem(R.id.general_activity_instalaciones_en_lista_menu_btn_mapa).setVisible(false);
        menu.findItem(R.id.menu_general_fragments_actionbar_menu_btn_buscar).setVisible(false);
        menu.findItem(R.id.map_fragment_menu_btn_mapa_type_settings).setVisible(false);
        menu.findItem(R.id.general_activity_instalaciones_en_lista_menu_btn_agregar_favorito).setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        Intent intent;
        // Handle action bar actions click
        switch (item.getItemId()) {
        //case R.id.action_settings:

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

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    //Este metodo antes era privado. Pero para poder llamarlo desde FavotirtosInstalacionesFragment lo he puesto como publico
    public void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        int pulsado = position-1;
        String tag = "";
        Log.d("Drawer", "Position: "+position+" Pulsado: "+pulsado);
        switch (position) {
        case 0:
            //Foto Perfil
            Log.d("Drawer", "Aukera 0");
            tag = "MENUPERFIL";
            //fragment = new HomeFragment();
            break;

        case 1:
            //Inicio
            Log.d("Drawer", "Aukera 1");
            tag = "MENUINICIO";
            fragment = new HomeFragment();

            break;
        case 2:
            //Avisos
            Log.d("Drawer", "Aukera 2");
            tag = "MENURSSAVISOS";
            fragment = new RssAvisosFragment();

            break;

            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();


            fragmentManager.beginTransaction().replace(R.id.main_frame_container, fragment, tag).commit();
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);

            setTitle(actionBarTitles[position-1]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        String tituloEnLaActionBar = (String) mTitle;   
        if(tituloEnLaActionBar.equalsIgnoreCase("Inicio")||tituloEnLaActionBar.equalsIgnoreCase("Hasiera")){

            mTitle = context.getString(R.string.app_name);;
        }

        SpannableString s = new SpannableString(mTitle);
        s.setSpan(new TypefaceSpan(this, "OpenSans-Semibold.ttf"), 0, s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        // Update the action bar title with the TypefaceSpan instance
        getActionBar().setTitle(s);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    public void disableDrawer(){

    }

}

In android manifest:

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

Style.xml

<style name="AppBaseTheme" parent="@android:Theme.Holo.Light">
    <!-- API 14 theme customizations can go here. -->
     <item name="android:actionBarStyle">@style/MyActionBarTheme</item>
     <item name="android:textColor">@color/texto_general</item>
    <item name="android:radioButtonStyle">@style/RadioButton</item>
2

There are 2 answers

4
Saraschandraa On

If you want to have the hamburger icon for the Navigation Drawer, Use the ActionBarDrawerToggle.syncState(), this will give you a default hamburger icon for the navigation drawer also when the drawer opens you will see the back button.

In your code set after mDrawerLayout.setDrawerListener(mDrawerToggle); put this

mDrawerToggle.syncState();
0
Anusha Harish On

You should use android.support.v7.app.ActionBarDrawerToggle. Check this link it might help you :)

How to implement DrawerArrowToggle from Android appcompat v7 21 library