简体   繁体   English

如何在导航抽屉上添加图标?

[英]How to add icons on navigation drawer?

I need you help :) I have already wrote my app, but now I need to add nav drawer to it. 我需要您的帮助:)我已经编写了我的应用程序,但是现在我需要向其添加导航抽屉。 I added nav drawer but I cant understand where should i put my icons. 我添加了导航抽屉,但是我不明白应该将图标放在哪里。 I want to put icons left of nav Items text like this: 我想在导航项目文本的左侧放置图标,如下所示:

pics "one" 图片“一个”

pics2 "two" pics2“两个”

pics3 "three" pics3“三”

hier is my java-code Settings.java hier是我的Java代码Settings.java

    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.res.Configuration;
    import android.os.Bundle;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;



/**
 * Created by vklamm on 31.03.2016.
 */
public class Settings extends AppCompatActivity {

    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    //declarations

    //Edittext fields for username , server, password & port information
    EditText edtIpurl, edtPort, edtUsername, edtPassword;
    //Textviews that can be clicked
    TextView databaseDel, databaseRef, magnumgmbh, contact, support;
    //imagebuttons for bottom menu
    ImageButton contacts, articles, invoices, orders;
    //string for server URL
    static String serverURL = "http://", port = ":", username = "", password ="";
    Thread newSettingsThread;
    static boolean hasVisited = false;
    SharedPreferences sp;
    static String MP = "MyPrefs";
    static String APS = "sURL", APP = "sport", APU = "uname", APPass = "pass";



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

        setTitle("Settings");


        mPlanetTitles = new String[]{"one", "two", "three"};
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);




        // Set the adapter for the list view
        //mDrawerList.setAdapter(new ArrayAdapter<String>(this,
        //        R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());





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

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                // set name if drawer closes
                //getSupportActionBar().setTitle("Settings");
                //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                //set name if drawer opens
                //getSupportActionBar().setTitle("Choose options");
                //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

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


        mDrawerList.bringToFront();
        mDrawerLayout.requestLayout();

        mDrawerToggle.isDrawerIndicatorEnabled();






    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    */


    //
    @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);
        mDrawerToggle.onConfigurationChanged(newConfig);
        Toast.makeText(Settings.this, "Drawer 2",
                Toast.LENGTH_SHORT).show();
    }

    //if u clicked on ||| or <- sign
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        Toast.makeText(Settings.this, "just call under the number +4917620279876 if you see it",
                Toast.LENGTH_LONG).show();
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    /**
     * Swaps fragments in the main content view
     */
    private void selectItem(int position) {
        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        //setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

/* set title
    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
        Toast.makeText(Settings.this, "Drawer 6",
                Toast.LENGTH_SHORT).show();
    }
*/

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);

            String positions = parent.getAdapter().getItem(position).toString();
            int p = position;

            switch (p){
                case 0:
                    Toast.makeText(Settings.this, "0", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(Settings.this, "1", Toast.LENGTH_SHORT).show();
                    break;
                default :
                    Toast.makeText(Settings.this, "3", Toast.LENGTH_SHORT).show();
            }


        }
    }
}

activity_settings.xml activity_settings.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
<!-- The navigation drawer -->
<ListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="@color/grayBackground"/>

drawer_list_item.xml 抽屉式清单_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/activated_background"
android:gravity="center_vertical"
android:minHeight="?attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />

drawable directory --- > activated_background.xml 可绘制目录---> Activated_background.xml

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@color/green" android:state_activated="true"/>
<item android:drawable="@color/green" android:state_selected="true"/>
<item android:drawable="@color/green" android:state_pressed="true"/>
<item android:drawable="@color/green" android:state_checked="true"/>
<item android:drawable="@android:color/transparent"/>

and some strings.xml 和一些strings.xml

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="refresh_button">refresh_button</string>
    <string name="prev_button">prev</string>


    <string name="drawer_open">Open</string>
    <string name="drawer_close">Close</string>
</resources>

You need to create your own adapter, define the layout of it's items so that it contains the icon and text, as you want, and then set it as the adapter of your drawer list. 您需要创建自己的适配器,定义其项目的布局,以便根据需要包含图标和文本,然后将其设置为抽屉列表的适配器。

So you need to modify your drawer_list_item.xml to contain a horizontal LinearView , with the icon ImageView and the label TextView . 因此,您需要修改您的drawer_list_item.xml以包含一个带有图标ImageView和标签TextView的水平LinearView

Here is an implementation I did for one of my projects that does exactly what you need to do: 这是我为我的一个项目所做的一种实现,它完全满足您的需要:

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public abstract class DrawerActivity extends BaseActivity {

    private static List<DrawerItem> sDrawerItems;

    private ActionBarDrawerToggle mDrawerToggle;

    public ActionBarDrawerToggle getDrawerToggle() {
        return mDrawerToggle;
    }

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

        setUpDrawerList();
        setUpDrawerToggle();
    }

    private void setUpDrawerToggle() {
        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_container);
        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, getToolbar(),
            R.string.drawer_open, R.string.drawer_close);
        drawerLayout.addDrawerListener(mDrawerToggle);
    }

    private void setUpDrawerList() {
        final DrawerAdapter drawerAdapter = new DrawerAdapter(this, getDrawerItems(), getClass());
        final int selectedPosition = drawerAdapter.getCurrentItemPosition();
        final ListView drawerList = (ListView) findViewById(R.id.drawer_list);
        drawerList.setAdapter(drawerAdapter);
        drawerList.setItemChecked(selectedPosition, true);
        drawerList.setOnItemClickListener(new DrawerItemOnClickListener());
    }

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

        mDrawerToggle.syncState();
    }

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

        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_drawer;
    }

    private static List<DrawerItem> getDrawerItems() {
        if (sDrawerItems == null) {
            sDrawerItems = new ArrayList<>();
            sDrawerItems.add(new DrawerItem(R.drawable.ic_today_black_24dp, R.string.calendar_title,
                BaseCalendarActivity.class));
            sDrawerItems.add(new DrawerItem(R.drawable.ic_face_black_24dp, R.string.profile_title, null));
            sDrawerItems.add(new DrawerItem(R.drawable.ic_list_black_24dp, R.string.services_title, null));
            sDrawerItems.add(new DrawerItem(R.drawable.ic_schedule_black_24dp, R.string.office_hours_title, null));
            sDrawerItems.add(new DrawerItem(R.drawable.ic_exit_to_app_black_24dp, R.string.logout, null));
        }

        return sDrawerItems;
    }

    // Encapsulates the information about a drawer item
    protected static class DrawerItem {

        public int iconResId;
        public int titleResId;
        public Class<? extends BaseActivity> targetClass;

        public DrawerItem(@DrawableRes int iconResId, @StringRes int titleResId,
            Class<? extends BaseActivity> targetClass) {
            this.iconResId = iconResId;
            this.titleResId = titleResId;
            this.targetClass = targetClass;
        }

    }

    protected static class DrawerAdapter extends ArrayAdapter<DrawerItem> {

        private final Class<? extends BaseActivity> mCurrentClass;

        public DrawerAdapter(Context context, List<DrawerItem> objects, Class<? extends BaseActivity> currentClass) {
            super(context, R.layout.list_item_drawer, objects);

            mCurrentClass = currentClass;
        }

        protected int getCurrentItemPosition() {
            for (int i = 0; i < getCount(); i++) {
                final DrawerItem item = getItem(i);
                if (mCurrentClass.equals(item.targetClass)) {
                    return i;
                }
            }

            return -1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_drawer, parent, false);

                final ViewHolder holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.drawer_item_icon);
                holder.title = (TextView) convertView.findViewById(R.id.drawer_item_title);

                convertView.setTag(holder);
            }

            final DrawerItem item = getItem(position);
            final ViewHolder holder = (ViewHolder) convertView.getTag();
            holder.icon.setImageResource(item.iconResId);
            holder.title.setText(item.titleResId);

            return convertView;
        }

        private class ViewHolder {

            public ImageView icon;
            public TextView title;
        }
    }

    private class DrawerItemOnClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final DrawerItem item = (DrawerItem) parent.getItemAtPosition(position);
            if (DrawerActivity.this.getClass().equals(item.targetClass)) {
                // do nothing when the same item is selected
                return;
            }

            if (item.targetClass == null) {
                Toast.makeText(DrawerActivity.this, getString(item.titleResId) + " is under construction",
                    Toast.LENGTH_SHORT).show();
                return;
            }

            final ListView drawerList = (ListView) parent;
            drawerList.setItemChecked(position, true);
            final Intent intent = new Intent(DrawerActivity.this, item.targetClass);
            startActivity(intent);
        }
    }
}

cabinet_list_item是列表视图的布局..在textview之前添加一个imageview ..创建一个与mplanettitles相同的图像数组,但制作一个drawables ..看起来像int [] mplanetimages = [r.drawable.something]然后创建一个自定义适配器..然后将字符串数组和图像的int数组传递给适配器,然后在适配器内部进行设置

Thank you all. 谢谢你们。 I found answer on another forum. 我在另一个论坛上找到了答案。 cyberforum.ru cyberforum.ru

hier we go. 嗨,我们走。

You need your own Adapter where you put your icons and labels and than you bind it to your view. 您需要使用自己的适配器,在其中放置图标和标签,然后将其绑定到视图。

So class MenuItem with data , icons and title 因此,将MenuItem与data,icons和title一起使用

public class MenuItem {
    private  String title;
    private int imageId;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
}

Transfer your created class to adpater and create menuHolder that binds to View 将您创建的类转移到adpater并创建绑定到View的menuHolder

import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    import java.util.List;

    /**
     * Created by vklamm on 08.04.2016.
     * transfer hier MenuItem class
     * create Menu holder and bind it to view
     */
    public class MyAdapter extends ArrayAdapter<MenuItem> {

        private int resource;
        private List<MenuItem> data;
        private Context context;
        private MenuHolder menuHolder;

        public MyAdapter(Context context, int resource, Context context1) {
            super(context, resource);
            context = context1;
        }

        public MyAdapter(Context context, int resource, List<MenuItem> data) {
            super(context, resource, data);
            this.context = context;
            this.resource = resource;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView==null){
                LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = layoutInflater.inflate(resource,parent,false);

                menuHolder = new MenuHolder();

                //create drawer_list_item layout where ours icons and labels are
                menuHolder.menuItemImg = (ImageView) convertView.findViewById(R.id.menuItemImg);
                menuHolder.menuItemTitle = (TextView) convertView.findViewById(R.id.menuItemTitle);
                convertView.setTag(menuHolder);
            }else {
                menuHolder = (MenuHolder) convertView.getTag();
            }

            MenuItem menuItem = data.get(position);
            if(menuItem!=null){
                menuHolder.menuItemImg.setImageResource(menuItem.getImageId());
                menuHolder.menuItemTitle.setText(menuItem.getTitle());
            }

            return convertView;
        }
        //created class for binding our icons and texts from view
        public class MenuHolder {
            ImageView menuItemImg;
            TextView menuItemTitle;
        }
    }

modifites/change drawer_list_item.xml to 修改/将drawer_list_item.xml更改为

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/menuItemImg" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/menuItemTitle" />
</LinearLayout>

now add to Settings.class 现在添加到Settings.class

List<de.magnum_gmbh.mw.MenuItem> menuItems = new ArrayList<>();
        //create your elements of navigation drawer
        de.magnum_gmbh.mw.MenuItem menuItem = new de.magnum_gmbh.mw.MenuItem();
String[] titles = {"Addresses", "Articles", "Invoices","Orders","Settings"};
        Integer[] images = {R.drawable.contacts,R.drawable.articles,R.drawable.invoices,R.drawable.orders,R.drawable.settings};
        for(int i=0;i<5;i++) {
            menuItem.setImageId(images[i]);
            menuItem.setTitle(title[i]);
            menuItems.add(menuItem);
            }
        //initialize your own adapter 
        mDrawerList.setAdapter(new MyAdapter(this, R.layout.drawer_list_item, menuItems));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM