Dep
Dep

Reputation: 183

How to add image to navigation drawer/ listeview?

New to Android, I have a navigation drawer which is working perfectly. But now I want to insert image for each of the option - like 1 image for "home" and another for "scan barcode" etc.

I did some tutorial search for this, but unable to find the suitable solution. Any suggestions? thanks in advance.

Navigation Drawer with ListView

NavigationDrawerFrag.xml

/**
 * .
 *
 */package com.androidatc.customviewindrawer;

//import android.support.v4.app.FragmentManager;
import android.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerListView;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    public NavigationDrawerFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }


        // Select either the default item (0) or the last selected item.
        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
                loadFragmentLayout(position);
            }
        });
        mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                new String[]{
                        getString(R.string.title_section1),
                        getString(R.string.title_section2),
                        getString(R.string.title_section3),
                        getString(R.string.title_section4),
                        getString(R.string.title_section5),
                }));
        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return mDrawerListView;
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     */
    private void loadFragmentLayout(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new MainViewFragment();
                break;
            case 1:
                fragment = new BarCodeScanFrag();
                break;
            case 2:
                fragment = new SearchBookFrag();
                break;
            case 3:
                fragment = new MyAccFrag();
                break;
            case 4:
//                fragment = new BorrowFrag();
                break;
            default:
                break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerListView.setItemChecked(position, true);
            mDrawerListView.setSelection(position);
            mDrawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

               // getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                //getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.global, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // it is for navigation menu
        Fragment fragment = null;
        if (mDrawerToggle.onOptionsItemSelected(item)) {
//            Toast.makeText(getActivity(), "Inside Toggle", Toast.LENGTH_SHORT).show();

            return true;
        }

        // below is not called for login. why?
//        Toast.makeText(getActivity(), item.getItemId() + "=" + R.id.action_login + "B4 Action Login.", Toast.LENGTH_SHORT).show();


//        if (item.getItemId() == R.id.action_logout) {
////            Toast.makeText(getActivity(), "Action Login.", Toast.LENGTH_SHORT).show();
//            fragment = new LoginFrag();
//
//            if (fragment != null) {
//                FragmentManager fragmentManager = getFragmentManager();
//                fragmentManager.beginTransaction()
//                        .replace(R.id.container, fragment).commit();
//
//
//            }
//
//            return true;
//        }
//        else {
//            Toast.makeText(getActivity(), "Home .", Toast.LENGTH_SHORT).show();
//            fragment = new HomeFrag();

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment).commit();


            }

            return true;
        }

//        return super.onOptionsItemSelected(item);
//    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.
     */
    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public static interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onNavigationDrawerItemSelected(int position);
    }
}

Fragment_navigation_drawer.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#cccc"
    tools:context=".NavigationDrawerFragment" />

Upvotes: 1

Views: 19630

Answers (8)

Mayank Bhatnagar
Mayank Bhatnagar

Reputation: 2191

You will have to make custom adapter for this case.

public class NavDrawerListAdapter extends BaseAdapter {
     
    private Context context;
    private ArrayList<NavDrawerItem> navDrawerItems;
     
    public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
        this.context = context;
        this.navDrawerItems = navDrawerItems;
    }
 
    @Override
    public int getCount() {
        return navDrawerItems.size();
    }
 
    @Override
    public Object getItem(int position) {       
        return navDrawerItems.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
        }
          
        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
        TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
          
        imgIcon.setImageResource(navDrawerItems.get(position).getIcon());        
        txtTitle.setText(navDrawerItems.get(position).getTitle());
         
        // displaying count
        // check whether it set visible or not
        if(navDrawerItems.get(position).getCounterVisibility()){
            txtCount.setText(navDrawerItems.get(position).getCount());
        }else{
            // hide the counter view
            txtCount.setVisibility(View.GONE);
        }
         
        return convertView;
    }
 
}

I got this from: here

Upvotes: 3

Cabezas
Cabezas

Reputation: 10767

When you put image in your navigation drawer you have to declare a layout, in this case relativeLayout. In layout xml you declare a layout, now you put image inside layout, then you put listView.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- main content -->

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <!-- Menu -->

    <RelativeLayout
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/degradee"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/image_view"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@drawable/theworldisyours" />

        <ListView
            android:id="@+id/list_view_drawer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@id/image_view"
            android:choiceMode="singleChoice" />
    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>

And now in your activity

public class MainActivity extends ActionBarActivity {

    private String[] mOptionMenu;
    private DrawerLayout mDrawerLayout;
    private RelativeLayout mDrawerRelativeLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mTitleSection;
    private CharSequence mTitleApp;
    private Fragment mFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mOptionMenu = new String[] { getString(R.string.first_fragment),
                getString(R.string.second_fragment),
                getString(R.string.third_fragment) };
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
        mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
        mDrawerList.setAdapter(new ArrayAdapter<String>(getSupportActionBar()
                .getThemedContext(), android.R.layout.simple_list_item_1,
                mOptionMenu));
        initContentWithFirstFragment();

        mDrawerList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                switch (position) {
                case 0:
                    mFragment = new FirstFragment();
                    break;
                case 1:
                    mFragment = new SecondFragment();
                    break;
                case 2:
                    mFragment = new ThirdFragment();
                    break;
                }

                FragmentManager fragmentManager = getSupportFragmentManager();

                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame, mFragment).commit();

                mDrawerList.setItemChecked(position, true);

                mTitleSection = mOptionMenu[position];
                getSupportActionBar().setTitle(mTitleSection);

                mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
            }
        });
        mDrawerList.setItemChecked(0, true);
        mTitleSection = getString(R.string.first_fragment);
        mTitleApp = getTitle();

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitleSection);
                ActivityCompat.invalidateOptionsMenu(MainActivity.this);
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(R.string.app_name);
                ActivityCompat.invalidateOptionsMenu(MainActivity.this);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
        case R.id.action_settings:
            Toast.makeText(this, R.string.action_settings, Toast.LENGTH_SHORT)
                    .show();
            ;
            break;
        default:
            return super.onOptionsItemSelected(item);
        }

        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    public void initContentWithFirstFragment(){

        mTitleSection =getString(R.string.first_fragment);
        getSupportActionBar().setTitle(mTitleSection);
        mFragment = new FirstFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();

        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, mFragment).commit();
    }
}

You can check this post and this example in GitHub

Upvotes: 1

Ajay Pandya
Ajay Pandya

Reputation: 2457

This is your base adapter class you have to set on listview of drawer

public class NavDrawerListAdapter extends BaseAdapter {

private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;

public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
    this.context = context;
    this.navDrawerItems = navDrawerItems;
}

@Override
public int getCount() {
    return navDrawerItems.size();
}

@Override
public Object getItem(int position) {       
    return navDrawerItems.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.drawer_list_item, null);
    }

    ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
    TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

    imgIcon.setImageResource(navDrawerItems.get(position).getIcon());        
    txtTitle.setText(navDrawerItems.get(position).getTitle());

    // displaying count
    // check whether it set visible or not
    if(navDrawerItems.get(position).getCounterVisibility()){
        txtCount.setText(navDrawerItems.get(position).getCount());
    }else{
        // hide the counter view
        txtCount.setVisibility(View.GONE);
    }

    return convertView;
}

Find full code from here

Upvotes: 1

Laxmeena
Laxmeena

Reputation: 790

Here I'm sharing some simple edit through you can achieve it easily.

Just edit nav_header_main.xml

<Button
    android:id="@+id/btn_home"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="3dp"
    android:background="@null"
    android:drawablePadding="6dp"
    android:drawableRight="@mipmap/grocery_logo"
    android:gravity="left|center"
    android:padding="6dp"
    android:text="Home"
    android:textColor="@color/colorPrimary" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"

    android:background="@color/border" />


<LinearLayout
    android:id="@+id/nav_quicklist_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="51dp"
        android:layout_weight="0.05"
        android:src="@mipmap/quicklist_menu" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:text="Quick List"
        android:textAlignment="center"
        android:textColor="@color/menu_text_color"
        android:textSize="13sp" />

</LinearLayout>

<TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/border" />


<LinearLayout
    android:id="@+id/nav_myaccount_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="51dp"
        android:layout_weight="0.05"
        android:src="@mipmap/my_account" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:text="My Account"
        android:textAlignment="center"
        android:textColor="@color/menu_text_color"
        android:textSize="13sp" />

</LinearLayout>

<TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/border" />

And in MainActivity.java class use this to get the design.

     NavigationView navigationView = (NavigationView)       findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    for (int i = 0; i < navigationView.getMenu().size(); i++) {
        MenuItem item = navigationView.getMenu().getItem(i);
        if (i != 2) {
            Drawable dr = item.getIcon();
            System.out.println(i + "-----drawable..." + dr);

            Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();

            Drawable d = new BitmapDrawable(getResources(),  Bitmap.createBitmap(bitmap, 0, 0, 72, 72));
            navigationView.getMenu().getItem(i).setIcon(d);
        }


    LinearLayout lay = (LinearLayout) navigationView.getHeaderView(0);
    Button btn_home = (Button) lay.findViewById(R.id.btn_home);
    btn_home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            fragment = new Home();
            if (fragment != null) {
                title_tv.setText("Grocery");
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
            }
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        }
    });
    LinearLayout nav1 = (LinearLayout) lay.findViewById(R.id.nav_quicklist_layout);
    nav1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            fragment = new CreateQuickList();
            if (fragment != null) {
                title_tv.setText("SRSGrocery");
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
            }
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        }
    });

    LinearLayout nav2 = (LinearLayout) lay.findViewById(R.id.nav_myaccount_layout);
    nav2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            fragment = new MyAccount();
            if (fragment != null) {
                title_tv.setText("SRSGrocery");
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
            }
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        }
    });

Upvotes: 1

Naresh Narsing
Naresh Narsing

Reputation: 785

You can checkout my github link where i had implemented this Github Link or you can also follow series of slidenerd tutorial Android RecyclerView Example Part 1: Android Material Design Tutorials where you can achieve what you want to implement

Upvotes: 1

Hussain ID
Hussain ID

Reputation: 231

Add this to your main activity :

     <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        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"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <!-- REST OF YOUR CONTENT-->


    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/drawer_menu"/>

</android.support.v4.widget.DrawerLayout>

Drawer Layout should be your root element:

Add new menu in menu.xml folder:

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:id="@+id/menu" android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@null"
            android:title="Home" />

        <item
            android:id="@+id/nav_settings"
            android:icon="@null"
            android:title="Settings" />

        <item
            android:id="@+id/nav_playlists"
            android:icon="@null"
            android:title="PlayLists" />
    </group>
</menu>

Add this to your main activity onCreate method:

final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
    };

    drawer.setDrawerListener(toggle);
    toggle.syncState();


    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

Do this :

   public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

... Your Code....

    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_settings:
                Intent settingsIntent = new Intent(this, SettingsActivity.class);
                startActivity(settingsIntent);
                break;
            case R.id.nav_playlists:
                Intent playlistsIntent = new Intent(this,PlayList.class);
                startActivity(playlistsIntent);
                break;
        }
        return false;
    }

Above code means implement Navigation item click listener and override the method. That's it!

Upvotes: 1

Muhammad Ibrahim
Muhammad Ibrahim

Reputation: 317

Create a separate xml layout, and add that layout as an Header to your listView.

try the following steps to learn it.

If you are using Android Studio,

  1. start a new sample project.
  2. Name your project. click Next. Select
  3. Minimum SDK. click Next.
  4. you will be prompted with "Add an Activity to Mobile".
  5. Select "Navigation Drawer Activity", and click Next.
  6. Create the project.

    Examine the project. you will get an idea.

enter image description here

Upvotes: 0

Linh
Linh

Reputation: 61009

In here you set the data for your ListView and it doesn't contain image

mDrawerListView.setAdapter(new ArrayAdapter<String>(
                    getActionBar().getThemedContext(),
                    android.R.layout.simple_list_item_activated_1,
                    android.R.id.text1,
                    new String[]{
                            getString(R.string.title_section1),
                            getString(R.string.title_section2),
                            getString(R.string.title_section3),
                            getString(R.string.title_section4),
                            getString(R.string.title_section5),
                    }));

If you want to add image to your ListView, you need to create a custom adapter which contains image for your ListView
Try Custom Listview with Image and Text using ArrayAdapter

Upvotes: 1

Related Questions