简体   繁体   English

如何在导航抽屉中添加图标

[英]How to add icon into navigation drawer

I blur with the complicate code which is all customize navigation drawer. 我模糊了所有自定义导航抽屉的复杂代码。 I just want create a simple navigation with icon only and it using fragment to swap the the content to be display when user click the navigation list. 我只想创建一个仅带图标的简单导航,它使用片段交换当用户单击导航列表时要显示的内容。

public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        android.app.Fragment objFragment = null;

        switch (position){
            case 0:
                objFragment = new Overview();
                mTitle = getString(R.string.title_section0);

                break;
            case 1:
                objFragment = new Income();
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                objFragment = new Expenses();
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                objFragment = new Category();
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                objFragment = new CashConverter();
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                objFragment = new History();
                mTitle = getString(R.string.title_section5);
                break;
        }


        // update the main content by replacing fragments
        android.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, objFragment)
                .commit();
    }

    public void onSectionAttached(int position) {
        switch (position) {
            case 0:
                mTitle = getString(R.string.title_section0);
                break;
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                mTitle = getString(R.string.title_section5);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

PlaceholderFragment PlaceholderFragment

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

there are 2 ways to do this. 有两种方法可以做到这一点。
1. you add the item for the navigation drawer manually. 1.您为导航抽屉手动添加项目。
2. still use list adapter but with overridden getView method and take advantage of TextView compound drawables. 2.仍使用列表适配器,但具有覆盖的getView方法,并利用TextView复合可绘制对象。 You can search for setCompoundDrawablesRelative for more info. 您可以搜索setCompoundDrawablesRelative以获得更多信息。

I'm not gonna post the first option since it would need to change many part of the code, but here is the example for the second option. 我不会发布第一个选项,因为它需要更改代码的许多部分,但是这里是第二个选项的示例。

Find the onCreateView method in your NavigationDrawerFragment class and adapt this pseudocode below to your code. NavigationDrawerFragment类中找到onCreateView方法,并将下面的伪代码改编为您的代码。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mDrawerListView = <get your navigation drawer list view here or leave it like the original>
    mDrawerListView.setOnItemClickListener(<for the click listener, again leave it like the original>);

    final LayoutInflater inflater1 = inflater; //this is for the child AdapterView to access the inflater

    mDrawerListView.setAdapter(new ArrayAdapter<String>(
            <get your context here>,
            R.layout.simple_activated_list,
            R.id.item,
            <your array of items to be listed in the drawer>
        ){
        @Override
        public View getView(int pos, View convertView, ViewGroup parent){
            super.getView(pos, convertView, parent);
            if(convertView == null) {
                // if the view is null, you need to inflate the view explicitly
                convertView = inflater1.inflate(R.layout.simple_activated_list, parent, false);
            }

            TextView tv = (TextView)convertView.findViewById(R.id.item);
            String str = getItem(pos); // for displaying your menu text, since you have overridden it
            Drawable d; // for setting up your icon and its size
            float density = getResources().getDisplayMetrics().density;
            tv.setText(str); // set the text
            // you can branch out by menu name or menu order (pos)
            switch(str){
                case "Your menu text":
                    // your specific menu item
                    d = getResources().getDrawable(R.drawable.ic_history);
                    break;
                default:
                    // else
                    d = getResources().getDrawable(R.drawable.ic_arrow);
                    break;
            }
            // set it to 24dp x 24dp
            d.setBounds(0,0,Math.round(24*density),Math.round(24*density));
            tv.setCompoundDrawablesRelative(d, null, null, null); // set the icon

            return convertView;
        }
    });

    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
} 

hope that helps 希望能有所帮助

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

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