NavigationDrawer抽屉导航栏(如知乎)简析

来源:互联网 发布:ubuntu 统计目录大小 编辑:程序博客网 时间:2024/05/21 11:00

1.NavigationDrawer抽屉导航栏特点说明


  • 1.这个例子说明了安卓底库自带的DrawerLayout布局控件的一般用法
  • 2.当一个左侧drawer式的导航栏存在时,活动的activity会检测Actionbar上的按钮是否被按下,以此来显示或者关闭导航栏
  • 3.ActionBarDrawerToggle有利于这种操作
  • 4.抽屉内的item(每一项)应分为两类:
    • 4.1视图切换 视图切换与列表或标签导航(如listview导航)遵循相同的基本策略,因此一个视图切换不会创建导航历史。 这种模式只能在一项任务的的根activity 中使用,即任何界面都能通过Actionbar触发出drawer式的抽屉导航栏
    • 4.2 item选择
  • 5.不建议使用右侧抽屉来导航,一般用于具体的点击事件。这是遵循导航栏以及触发他的Actionbar按钮应居左而具体的点击事件按钮应居右 的模式的指导。
  • 6.一个事件应当在当前的窗口上进行操作,举例来说启用或者禁用当前的数据覆盖

2.代码详解

activity_main.xml

DrawerLayout布局为android-support-v4.jar包自带,drawerLayout其实是一个布局控件,跟LinearLayout等控件是一种东西,但是drawerLayout带有滑动的功能。只要按照drawerLayout的规定布局方式写完布局,就能有侧滑的效果。
有两点要注意:主内容区的布局代码要放在侧滑菜单布局的前面,这可以帮助DrawerLayout判断谁是侧滑菜单,谁是主内容区;侧滑菜单的部分的布局(这里是ListView)可以设置layout_gravity属性,他表示侧滑菜单是在左边还是右边。

<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">    <FrameLayout        android:id="@+id/content_frame"        android:layout_width="match_parent"        android:layout_height="match_parent" />    <!-- android:layout_gravity="start" tells DrawerLayout to treat         this as a sliding drawer on the left side for left-to-right         languages and on the right side for right-to-left languages.         The drawer is given a fixed width in dp and extends the full height of         the container. A solid background is used for contrast         with the content view. -->    <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="#111"/></android.support.v4.widget.DrawerLayout>

fragment_planet.xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/image"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#000000"    android:gravity="center"    android:padding="32dp" />

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="wrap_content"    android:padding="16dp"    android:gravity="center_vertical"    android:background="@drawable/activated_background"    >    <ImageView         android:id="@+id/item_icon"        android:layout_marginRight="10dp"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <TextView         android:id="@+id/item_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textAppearance="?android:attr/textAppearanceListItemSmall"        android:textColor="@drawable/text_color_primary_invertible"        android:gravity="center_vertical"    /></LinearLayout>

DrawerListItem.java

导航栏控件信息类

package com.hujin.navigationviewer;import android.graphics.drawable.Drawable;public class DrawerListItem {    private Drawable icon;  //控件图标    private String title;   //控件文字说明    public DrawerListItem() {    }    public DrawerListItem(Drawable icon, String title) {        this.icon = icon;        this.title = title;    }    public Drawable getIcon() {        return icon;    }    public String getTitle() {        return title;    }    public void setIcon(Drawable icon) {        this.icon = icon;    }    public void setTitle(String title) {        this.title = title;    }}

DrawerListAdapter.java

这里适配器没有做优化,优化代码最后附上,这里只是做个说明

package com.hujin.navigationviewer;import java.util.List;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 DrawerListAdapter extends BaseAdapter {    private LayoutInflater mInflater;    private List<DrawerListItem> mItems;    public DrawerListAdapter(Context context, List<DrawerListItem> data) {        this.mInflater = LayoutInflater.from(context);        this.mItems = data;    }    @Override    public int getCount() {        return mItems.size();    }    @Override    public DrawerListItem getItem(int position) {        return mItems.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        DrawerListItem item = getItem(position);        TextView itemTitle = null;        ImageView itemIcon = null;        if(convertView == null){            convertView = mInflater.inflate(R.layout.drawer_list_item, null);        }        itemTitle = (TextView) convertView.findViewById(R.id.item_title);         itemIcon = (ImageView) convertView.findViewById(R.id.item_icon);        itemTitle.setText(item.getTitle());        itemIcon.setBackground(item.getIcon());        return convertView;    }}

MainActivity.java

package com.hujin.navigationviewer;import java.util.ArrayList;import java.util.List;import java.util.Locale;import android.app.Activity;import android.app.Fragment;import android.app.FragmentManager;import android.app.SearchManager;import android.content.Intent;import android.content.res.Configuration;import android.os.Bundle;import android.support.v4.app.ActionBarDrawerToggle;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;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.ImageView;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends Activity {    private DrawerLayout mDrawerLayout;    private ListView mDrawerListView;    private ActionBarDrawerToggle mDrawerToggle;    private CharSequence mDrawerTitle;    private CharSequence mTitle;    private String[] mPlanetTitles;    private List<DrawerListItem> mData = new ArrayList<DrawerListItem>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTitle = mDrawerTitle = getTitle();        mPlanetTitles = getResources().getStringArray(R.array.planets_array); //侧边栏文字集合        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);        mDrawerListView  = (ListView) findViewById(R.id.left_drawer);  //left_drawer是listview控件,在DrawerLayout布局中        // set a custom shadow that overlays the main content when the drawer opens        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); //设置shadow        // set up the drawer's list view with items and click listener        int[] itemIconRes = {                R.drawable.ic_drawer_collect_normal,                R.drawable.ic_drawer_explore_normal,                R.drawable.ic_drawer_follow_normal,                R.drawable.ic_drawer_collect_normal,                R.drawable.ic_drawer_draft_normal,                R.drawable.ic_drawer_question_normal,                R.drawable.ic_drawer_setting_normal};        //List<DrawerListItem>添加元素        for (int i = 0; i < itemIconRes.length; i++) {            DrawerListItem item = new DrawerListItem(getResources().getDrawable(itemIconRes[i]), mPlanetTitles[i]);            mData.add(item);        }          //mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, mPlanetTitles));        //上句代码为简单的适配器加载方式,因需要listview丰富点,有图标有文字所以弃用        /////加载适配器        DrawerListAdapter adapter = new DrawerListAdapter(this, mData);        mDrawerListView.setAdapter(adapter);        mDrawerListView .setOnItemClickListener(new DrawerItemClickListener());        // enable ActionBar app icon to behave as action to toggle nav drawer        getActionBar().setDisplayHomeAsUpEnabled(true);  // 给左上角图标的左边加上一个返回的图标 。对应ActionBar.DISPLAY_HOME_AS_UP        getActionBar().setHomeButtonEnabled(true);  //决定左上角的图标是否可以点击。 true 图标可以点击  false 不可以点击。        // ActionBarDrawerToggle ties together the the proper interactions        // between the sliding drawer and the action bar app icon        //drawerLayout左侧菜单(或者右侧)的展开与隐藏可以被DrawerLayout.DrawerListener的实现监听到,这样你就可以在菜单展开与隐藏反生的时刻做一些希望做的事情,        //比如更新actionbar菜单等。如果你的activity有actionbar的话,还是建议你用ActionBarDrawerToggle来监听,ActionBarDrawerToggle实现了DrawerListener,        //所以他能做DrawerListener可以做的任何事情,同时他还能将drawerLayout的展开和隐藏与actionbar的app 图标关联起来,当展开与隐藏的时候图标有一定的平移效果,点击图标的时候还能展开或者隐藏菜单。        mDrawerToggle = new ActionBarDrawerToggle(                this,                  /* host Activity */                mDrawerLayout,         /* DrawerLayout object */                R.drawable.ic_drawer,  /* 点击触发抽屉导航栏的图标 */                R.string.drawer_open,  /* "open drawer" description for accessibility */                R.string.drawer_close  /* "close drawer" description for accessibility */                ) {            public void onDrawerClosed(View view) {  //导航栏关闭的触发事件                getActionBar().setTitle(mTitle);                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()            }            public void onDrawerOpened(View drawerView) { //导航栏开启的触发事件                getActionBar().setTitle(mDrawerTitle);                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()            }        };        mDrawerLayout.setDrawerListener(mDrawerToggle);  //导航栏设置监听        if (savedInstanceState == null) {            selectItem(0);        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        MenuInflater inflater = getMenuInflater();        inflater.inflate(R.menu.main, menu);        return super.onCreateOptionsMenu(menu);    }    /* Called whenever we call invalidateOptionsMenu() */     //onDrawerClosed与onDrawerOpened调用的方法    @Override    public boolean onPrepareOptionsMenu(Menu menu) {        // If the nav drawer is open, hide action items related to the content view        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerListView );        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);        return super.onPrepareOptionsMenu(menu);    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {         // The action bar home/up action should open or close the drawer.         // ActionBarDrawerToggle will take care of this.        if (mDrawerToggle.onOptionsItemSelected(item)) {            return true;        }        // Handle action buttons        switch(item.getItemId()) {        case R.id.action_websearch:            // create intent to perform web search for this planet            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());            // catch event that there's no activity to handle intent            if (intent.resolveActivity(getPackageManager()) != null) {                startActivity(intent);            } else {                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();            }            return true;        default:            return super.onOptionsItemSelected(item);        }    }    /* The click listner for ListView in the navigation drawer */    private class DrawerItemClickListener implements ListView.OnItemClickListener {        @Override        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            selectItem(position); //position所在位置被触发的方法        }    }    private void selectItem(int position) {        // update the main content by replacing fragments        Fragment fragment = new PlanetFragment();        Bundle args = new Bundle();        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);        fragment.setArguments(args);        FragmentManager fragmentManager = getFragmentManager();        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();        // update selected item and title, then close the drawer        mDrawerListView .setItemChecked(position, true);        setTitle(mPlanetTitles[position]);  //将标签文字设置为选中的item项的文字        mDrawerLayout.closeDrawer(mDrawerListView );    }    @Override//设置Actionbar标题    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);    }    /**     * Fragment that appears in the "content_frame", shows a planet     */     //内部类PlanetFragment    public static class PlanetFragment extends Fragment {        public static final String ARG_PLANET_NUMBER = "planet_number";        public PlanetFragment() {            // Empty constructor required for fragment subclasses        }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);            int i = getArguments().getInt(ARG_PLANET_NUMBER);            String planet = getResources().getStringArray(R.array.planets_array)[i];            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),                            "drawable", getActivity().getPackageName());            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);            getActivity().setTitle(planet);            return rootView;        }    }}

strings.xml

<resources>    <string name="app_name">Navigation Drawer Example</string>    <string-array name="planets_array">        <item>Mercury</item>        <item>Venus</item>        <item>Earth</item>        <item>Mars</item>        <item>Jupiter</item>        <item>Saturn</item>        <item>Uranus</item>        <item>Neptune</item>    </string-array>    <string name="drawer_open">Open navigation drawer</string>    <string name="drawer_close">Close navigation drawer</string>    <string name="action_websearch">Web search</string>    <string name="app_not_available">Sorry, there\'s no web browser available</string></resources>

demo代码

demo代码链接:http://download.csdn.net/detail/bruce_shan/9485005


0 0