How to Add icons adjacent to titles for Android Navigation Drawer

前端 未结 4 791
太阳男子
太阳男子 2020-12-13 21:28

I am currently working on an android app for 4.2.2 that uses the new NavigationDrawer. It works like a charm except for adding icons.

I found some sample code in wh

相关标签:
4条回答
  • 2020-12-13 21:48

    With recent versions of Support Library, the easiest way is to use a NavigationView. Here is a nice tutorial, and here is the official documentation.

    A NavigationView is included as second view in the DrawerLayout (instead of ListView from OP code), for example:

         <android.support.design.widget.NavigationView
         android:id="@+id/navigation"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:menu="@menu/left_menu" />
    

    Then, the menu should be populated with titles and icons, like (left_menu.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group
        android:id="@+id/leftMenuId"
        android:checkableBehavior="single">
        <item
            android:id="@+id/item1"
            android:icon="@drawable/ic_zzblack_24dp"
            android:title="Title1" />
        <item
            android:id="@+id/settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="Settings" />
    </group>
    </menu>
    

    For more details, please refer to the first link.

    0 讨论(0)
  • 2020-12-13 22:04

    Simplest way I did it is this way:

    1. Make this as your drawer xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tashan="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:orientation="horizontal"
    android:padding="@dimen/spacing_small" >
    
    <ImageView
        android:id="@+id/drawer_item_icons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/spacing_small"
        android:layout_marginStart="@dimen/spacing_small"
        android:contentDescription="@string/test_string"/>
    
    <TextView
        android:id="@+id/drawer_item_labels"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/spacing_normal"
        android:layout_marginStart="@dimen/spacing_small"
        android:paddingLeft="@dimen/spacing_small"
        android:paddingRight="@dimen/spacing_small"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#58585b" />
    
    </LinearLayout>
    

    2. Add these values to your 'dimens.xml'. Never hardcode values!

        <dimen name="spacing_normal">16dp</dimen>
        <dimen name="spacing_small">8dp</dimen>
    

    3. For Icons array add this String Array to 'strings.xml

    <string-array name="array_main_menu">
        <item>@drawable/1</item>
        <item>@drawable/2</item>
        <item>@drawable/3</item>
        <item>@drawable/4</item>
        <item>@drawable/5</item>
    </string-array>
    

    4. In your Adapter access this array by using a Typed Array instance.

        TypedArray typedArray=getResources().obtainTypedArray(R.array.array_main_menu);
    

    5. Inside the getView of your adapter, set image to Imageview like this.

     mIcon.setImageResource(typedArray.getResourceId(position, -1));
    

    here mIcon is your ImageView.

    0 讨论(0)
  • 2020-12-13 22:10

    here's my layout:

    <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" >
    
      <ImageView
        android:id="@+id/drawer_item_icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="10sp"
        android:layout_marginRight="10sp"
        android:src="@drawable/ic_launcher" />
    
      <TextView
        android:id="@+id/drawer_item_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:textSize="25sp"
        android:paddingTop="8sp"
        android:paddingBottom="8sp"
        android:paddingLeft="15sp" />
    
    </LinearLayout>
    
    0 讨论(0)
  • 2020-12-13 22:12

    You can use a custom list view along with the list adapter to display the counter besides the list item in the drawer. And then add whatever code you want to your counter method. Here's the code I implemented in my navigation drawer supported android app :

    getter/setter methods class for the drawer :

    package info.aea.drawer;
    
    public class NavDrawerItem {
    
        private String title;
        private String tag;
        private int icon;
        private String count = "0";
        // boolean to set visibility of the counter
        private boolean isCounterVisible = false;
    
        public NavDrawerItem(){}
    
        public NavDrawerItem(String title, String tag, int icon){
            this.title = title;
            this.tag = tag;
            this.icon = icon;
        }
    
        public NavDrawerItem(String title, String tag, int icon, boolean isCounterVisible, String count){
            this.title = title;
            this.tag = tag;
            this.icon = icon;
            this.isCounterVisible = isCounterVisible;
            this.count = count;
        }
    
        public String getTitle(){
            return this.title;
        }
    
        public String getTag(){
            return this.tag;
        }
    
        public int getIcon(){
            return this.icon;
        }
    
        public String getCount(){
            return this.count;
        }
    
        public boolean getCounterVisibility(){
            return this.isCounterVisible;
        }
    
        public void setTitle(String title){
            this.title = title;
        }
    
        public void setTag(String tag){
            this.tag = tag;
        }
    
        public void setIcon(int icon){
            this.icon = icon;
        }
    
        public void setCount(String count){
            this.count = count;
        }
    
        public void setCounterVisibility(boolean isCounterVisible){
            this.isCounterVisible = isCounterVisible;
        }
    }
    

    This is the list adapter I used to display the list. check the display count method in the end :

    package info.aea.drawer;
    
    import info.aea.snippets.R;
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    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 txtTag = (TextView) convertView.findViewById(R.id.tag);
            TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
    
            imgIcon.setImageResource(navDrawerItems.get(position).getIcon());        
            txtTitle.setText(navDrawerItems.get(position).getTitle());
            txtTag.setText(navDrawerItems.get(position).getTag());
    
            // 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;
        }
    
    }
    

    Corresponding list layout :

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:background="@drawable/list_selector">
    
        <ImageView
            android:id="@+id/icon"
            android:layout_width="25dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:contentDescription="@string/desc_list_item_icon"
            android:src="@drawable/ic_home"
            android:layout_centerVertical="true" />
    
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_toRightOf="@id/icon"
            android:minHeight="?android:attr/listPreferredItemHeightSmall"
            android:textAppearance="?android:attr/textAppearanceListItemSmall"
            android:textColor="@color/list_item_title"
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:paddingRight="40dp"/>
    
        <TextView android:id="@+id/counter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/counter_bg"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:textColor="@color/counter_text_color"/>
    
        <TextView
            android:id="@+id/tag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/icon"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="12dp"
            android:textColor="#999967"
            android:textSize="13sp"
            android:textStyle="italic"
            android:text="sample" />
    
    </RelativeLayout>
    

    and here's the main N-drawer class :

    package info.aea.launch;
    
    
    import info.aea.drawer.NavDrawerItem;
    import info.aea.drawer.NavDrawerListAdapter;
    import info.aea.snippets.R;
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.Intent;
    import android.content.res.Configuration;
    import android.content.res.TypedArray;
    import android.os.Bundle;
    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.widget.DrawerLayout;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.Toast;
    
    public class LaunchActivity_NavDrawer extends Activity {
    
    
    
    
        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;
    
        // nav drawer title
        private CharSequence mDrawerTitle;
    
        // used to store app title
        private CharSequence mTitle;
    
        // slide menu items
        private String[] navMenuTitles;
        private String[] navMenuTags;;
        private TypedArray navMenuIcons;
    
        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            SnippetsDB_Helper logindb;
            logindb=new SnippetsDB_Helper(this);
            //logindb=logindb.open();
    
    
    
    
            mTitle = mDrawerTitle = getTitle();
    
            // load slide menu items
            navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    
            // load slide menu tags
            navMenuTags = getResources().getStringArray(R.array.nav_drawer_tags);
    
            // nav drawer icons from resources
            navMenuIcons = getResources()
                    .obtainTypedArray(R.array.nav_drawer_icons);
    
            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    
            navDrawerItems = new ArrayList<NavDrawerItem>();
    
            // adding nav drawer items to array
            // Home
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuTags[0], navMenuIcons.getResourceId(0, -1), true, "22" ));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuTags[1], navMenuIcons.getResourceId(1, -1)));
            // Photos
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuTags[2], navMenuIcons.getResourceId(2, -1)));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuTags[3],  navMenuIcons.getResourceId(3, -1), true, "22"));
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuTags[4], navMenuIcons.getResourceId(4, -1)));
            // What's hot, We  will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuTags[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuTags[6], navMenuIcons.getResourceId(6, -1)));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuTags[7], navMenuIcons.getResourceId(7, -1), true, "22"));
    
            // empty list
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuTags[8], navMenuIcons.getResourceId(8, -1)));
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuTags[9], navMenuIcons.getResourceId(9, -1)));
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuTags[10], navMenuIcons.getResourceId(10, -1)));
    
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[11], navMenuTags[11], navMenuIcons.getResourceId(11, -1)));
    
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[12], navMenuTags[12], navMenuIcons.getResourceId(12, -1)));
    
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[13], navMenuTags[13], navMenuIcons.getResourceId(13, -1)));
    
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[14], navMenuTags[14], navMenuIcons.getResourceId(14, -1)));
    
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[15], navMenuTags[15], navMenuIcons.getResourceId(15, -1)));
    
    
    
    
    
            // 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) {
                    getActionBar().setTitle(mTitle);
                    // calling onPrepareOptionsMenu() to show action bar icons
                    invalidateOptionsMenu();
                }
    
                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                    // calling onPrepareOptionsMenu() to hide action bar icons
                    invalidateOptionsMenu();
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);
    
            if (savedInstanceState == null) {
                // on first time display view for first nav item
                displayView(0);
            }
        }
    
        /**
         * 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.main_menu, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            // Handle action bar actions click
            switch (item.getItemId()) {
    
            case R.id.action_settings:
                Toast.makeText(getApplicationContext(), "code", Toast.LENGTH_LONG).show();
                // Create new fragment and transaction
                Fragment newFragment = new Fragment_Java(); 
                // consider using Java coding conventions (upper char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.frame_container, newFragment);
                transaction.addToBackStack(null);
                // Commit the transaction
                transaction.commit(); 
                return true;
    
            case R.id.item1:
                Toast.makeText(getApplicationContext(), "send a suggestion", Toast.LENGTH_LONG).show();
                return true;
    
            case R.id.item2:
                Toast.makeText(getApplicationContext(), "Meet developers", Toast.LENGTH_LONG).show();
                return true;
    
            case R.id.item3:
                Toast.makeText(getApplicationContext(), "Rate this app", Toast.LENGTH_LONG).show();
                return true;
    
            default:
                return super.onOptionsItemSelected(item);
            }
        }
    
        /* 
         * Called when invalidateOptionsMenu() is triggered
         **/
    
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
            return super.onPrepareOptionsMenu(menu);
        }
    
    
    
    
    
        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
            // update the main content by replacing fragments
            Fragment fragment = null;
            switch (position) {
            case 0:
                fragment = new Fragment_a();
                break;
            case 1:
                fragment = new Fragment_b();
                break;
            case 2:
                fragment = new Fragment_C();
                break;   
            default:
                break;
            }
    
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();
    
                // update selected item and title, then close the drawer
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        }
    
        @Override
        public void setTitle(CharSequence title) {
            mTitle = title;
            getActionBar().setTitle(mTitle);
        }
    
        /**
         * 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);
        }
    
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent result) {
           super.onActivityResult(requestCode, resultCode, result);
        }
    }
    
    0 讨论(0)
提交回复
热议问题