您的位置:首页 > 其它

侧滑菜单 Navigation Drawer

2015-09-03 10:02 253 查看

侧滑菜单 Navigation Drawer

侧滑抽屉菜单是常见的Android菜单设计方案,节省屏幕面积,而又易于呼出,尤其配上Material Design ,个人感觉在设计上面是优于ios上面的Dock栏的。

下面基于DrawerLayout实现侧滑抽屉菜单。

1.创造Drawer Layout (Create a Drawer Layout)

activiy_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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

        <!-- The main content view -->
        <!-- 主要内容视图,抽屉菜单隐藏时间现实的界面 -->
        <!-- main content view 主视图必须是DrawerLayout的第一个子节点 ,宽度高度为填充父窗口 -->

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <!-- The navigation drawer -->
        <!-- 导航抽屉菜单,layout——gravity =start  从左向右 -->
        <!--  android:layout_width="240dp"  -->

        <ListView
            android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="#DAE1DD"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>


2.初始化DrawList ( Initialize the Drawer List )

MainActivity.java

package com.example.drawertoggle;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
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.ArrayAdapter;
import android.widget.ListView;

//跟leftDrawer最重要的差别,只有抽屉惨淡开启 actionbar 更多按钮自动隐藏
//抽屉菜单 开启 关闭事件 

public class MainActivity extends Activity {
    //DrawerLayout
    private DrawerLayout mDrawerLayout;
    //启动器
    private ActionBarDrawerToggle mDrawerToggle;
    //Drawer 标题
    private CharSequence mDrawerTitle;
    //actionbar 标题
    private CharSequence mTitle;

    private String[] mPlanetTitles;
    private ListView mDrawerList;

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

        //实例化
        mPlanetTitles = new String[] { "001", "002", "003" };
        mTitle = mDrawerTitle = getTitle();
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_launcher, R.string.open, R.string.close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                // creates call to onPrepareOptionsMenu()
                // 会创造 onPrepareOptionsMenu()的调用
                invalidateOptionsMenu(); 
            }

            //当抽屉菜单打开,回调此方法
            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
                // 创造onPrepareOptionMenu的調用
                invalidateOptionsMenu(); // creates call to
                                            // onPrepareOptionsMenu()
            }
        };

        // Set the drawer toggle as the DrawerListener
        // 设置抽屉菜单的启动器
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content
        // view
        // 抽屉菜单开启时,actionbar上面的item隐藏
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
    @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);
    }

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

            selectItem(position);
        }

    }

    /** Swaps fragments in the main content view */
    private void selectItem(int position) {
        // Create a new fragment and specify the planet to show based on
        // position
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        // args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        args.putInt("INDEX", position);
        //fragment传递数据
        fragment.setArguments(args);

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment).commit();
        //高亮被选择的选项,更新title ,关闭抽屉菜单
        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @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.

          if (mDrawerToggle.onOptionsItemSelected(item)) {
              return true;
            }
            // Handle your other action bar items...

            return super.onOptionsItemSelected(item);
    }

}


3.其他资源文件和辅助fragment

PlanetFragment.java

package com.example.drawertoggle;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class PlanetFragment extends Fragment {
    static String ARG_PLANET_NUMBER="position_index";
    int position=0;
    private TextView myTextView;

    @Override   
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //fragment.setArguments(args);
        //是官方推荐Fragment.setArguments(Bundle bundle)这种方式来传递参数
        position=getArguments().getInt("INDEX");
        Log.i("DrawerMenu", "PlanetFragment-----onCreate()");

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=inflater.inflate(R.layout.planet_fragment, null, false);
        myTextView=(TextView)view.findViewById(R.id.MyTextView);
        myTextView.setText(position+"   ssss");
        Log.i("DrawerMenu", "PlanetFragment-----onCreateView()");
        return view;
    }

}


drawer_list_item.xml (ListView item 布局 ,TextView最外层节点)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:textColor="#F59446" 
    android:padding="10dp"
    android:textSize="20sp"    
    android:text="try">

</TextView>


planet_fragment.java

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

    <TextView 
        android:id="@+id/MyTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="20dp"></TextView>

</LinearLayout>


array.xml

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

    <string-array name="heromatch">
        <item name="hero1">力量</item>
        <item name="hero2">敏捷</item>
        <item name="hero3">智力</item>
    </string-array>

</resources>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: