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

时间:2016-04-07 15:34:21

标签: java android xml navigation navigation-drawer

我需要你的帮助:)我已经写了我的应用程序,但现在我需要添加导航抽屉。我添加了导航抽屉,但我不明白我应该把我的图标放在哪里。我想把导航项目文本留下的图标如下:

pics" one"

pics2"两个"

pics3"三"

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

<?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

<?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目录---&gt; 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"/>

和一些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>

2 个答案:

答案 0 :(得分:0)

您需要创建自己的适配器,根据需要定义其项目的布局,使其包含图标和文本,然后将其设置为抽屉列表的适配器。

因此,您需要修改drawer_list_item.xml以包含水平LinearView,图标为ImageView,标签为TextView

以下是我为我的一个项目所做的实现,它完全符合您的需要:

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);
        }
    }
}

答案 1 :(得分:0)

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