Android SlidingMenu 开源项目使用示例(一)

SlidingMenu简介
SlidingMenu的是一种比较新的设置界面或配置界面效果,在主界面左滑或者右滑出现设置界面,能方便的进行各种操作.目前有大量的应用都在使用这一效果。如Evernote、Google+、Foursquare等,国内的豌豆夹,人人,360手机助手等都使用SlidingMenu的界面方案。


SlidingMenu github项目地址:https://github.com/jfeinstein10/SlidingMenu



关于SlidingMenu Demo导入 请参考前一篇文章,这里不重复介绍了。


SlidingMenu 常用属性介绍
mSlidingMenu.setMode(SlidingMenu.LEFT);//设置左滑菜单
mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//设置滑动的屏幕范围,该设置为全屏区域都可以滑动
mSlidingMenu.setShadowDrawable(R.drawable.shadow);//设置阴影图片
mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width);//设置阴影图片的宽度
mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);//SlidingMenu划出时主页面显示的剩余宽度
mSlidingMenu.setBehindWidth(400);//设置SlidingMenu菜单的宽度
mSlidingMenu.setFadeDegree(0.35f);//SlidingMenu滑动时的渐变程度
mSlidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);//使SlidingMenu附加在Activity上
mSlidingMenu.setMenu(R.layout.menu_layout);//设置menu的布局文件
mSlidingMenu.toggle();//动态判断自动关闭或开启SlidingMenu
mSlidingMenu.showMenu();//显示SlidingMenu
mSlidingMenu.showContent();//显示内容
mSlidingMenu.setOnOpenListener(onOpenListener);//监听SlidingMenu打开
关于关闭menu有两个监听,简单的来说,对于menu close事件,一个是when,一个是after 
mSlidingMenu.OnClosedListener(OnClosedListener);//监听SlidingMenu关闭时事件
mSlidingMenu.OnClosedListener(OnClosedListener);//监听SlidingMenu关闭后事件

mSlidingMenu.setMode(SlidingMenu.LEFT_RIGHT);//设置左右都可以划出SlidingMenu菜单
mSlidingMenu.setSecondaryMenu(R.layout.frame_menu);//设置右侧菜单的布局文件

mSlidingMenu.setSecondaryShadowDrawable(R.drawable.shadowright);//右侧菜单的阴影图片


使用Fragment实现SlidingMenu
1.首先Activity继承自SlidingMenu包下的SlidingFragmentActivity
2. setContentView(R.layout.content_frame);//该layout为一个全屏的FrameLayout
3. setBehindContentView(R.layout.menu_frame);//设置SlidingMenu使用的布局,同样是一个全屏的FrameLayout

4.设置SlidingMenu左侧菜单的Fragment


frame_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


frame_content.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


布局文件准备好了后,新建一个 Activity来继承SlidingActivity(如果需要使用Support V4兼容包,请继承SlidingFragmentActivity)

package com.example.slidingmenufragmenttest;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.slidingmenufragmenttest.fragment.CommunityFragment;
import com.example.slidingmenufragmenttest.fragment.FindPeopleFragment;
import com.example.slidingmenufragmenttest.fragment.HomeFragment;
import com.example.slidingmenufragmenttest.fragment.MenuFragment;
import com.example.slidingmenufragmenttest.fragment.MenuFragment.SLMenuListOnItemClickListener;
import com.example.slidingmenufragmenttest.fragment.PagesFragment;
import com.example.slidingmenufragmenttest.fragment.PhotosFragment;
import com.example.slidingmenufragmenttest.fragment.WhatsHotFragment;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity;

public class MainActivity extends SlidingActivity implements SLMenuListOnItemClickListener{
	//	public class MainActivity extends SlidingFragmentActivity {
	
	private SlidingMenu mSlidingMenu;
	
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setTitle("Home");
//		setTitle(R.string.sliding_title);
        setContentView(R.layout.frame_content);

        //1、 set the Behind View
        setBehindContentView(R.layout.frame_menu);
        
        // customize the SlidingMenu
        mSlidingMenu = getSlidingMenu();
//      mSlidingMenu.setMenu(R.layout.frame_menu);	//设置左侧菜单的布局文件
//      mSlidingMenu.setSecondaryMenu(R.layout.frame_menu);	设置右侧菜单的布局文件
        
//      mSlidingMenu.setShadowWidth(5);
//      mSlidingMenu.setBehindOffset(100);
        mSlidingMenu.setShadowDrawable(R.drawable.drawer_shadow);//设置阴影图片
        mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); //设置阴影图片的宽度
        mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); //SlidingMenu划出时主页面显示的剩余宽度
        mSlidingMenu.setFadeDegree(0.35f);
        //设置SlidingMenu 的手势模式
        //TOUCHMODE_FULLSCREEN 全屏模式,在整个content页面中,滑动,可以打开SlidingMenu
        //TOUCHMODE_MARGIN 边缘模式,在content页面中,如果想打开SlidingMenu,你需要在屏幕边缘滑动才可以打开SlidingMenu
        //TOUCHMODE_NONE 不能通过手势打开SlidingMenu
        mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

        //设置 SlidingMenu 内容
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        MenuFragment menuFragment = new MenuFragment();
        fragmentTransaction.replace(R.id.menu, menuFragment);
        fragmentTransaction.replace(R.id.content, new HomeFragment());
        fragmentTransaction.commit();
        
        //使用左上方icon可点,这样在onOptionsItemSelected里面才可以监听到R.id.home
        getActionBar().setDisplayHomeAsUpEnabled(true);
	}

    @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) {
        switch (item.getItemId()) {
        case android.R.id.home:
            
            toggle(); //动态判断自动关闭或开启SlidingMenu
//          getSlidingMenu().showMenu();//显示SlidingMenu
//          getSlidingMenu().showContent();//显示内容
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

	@SuppressLint("NewApi")
	@Override
	public void selectItem(int position, String title) {
		// update the main content by replacing fragments  
	    Fragment fragment = null;  
	    switch (position) {  
	    case 0:  
	        fragment = new HomeFragment();  
	        break;  
	    case 1:  
	        fragment = new FindPeopleFragment();  
	        break;  
	    case 2:  
	        fragment = new PhotosFragment();  
	        break;  
	    case 3:  
	        fragment = new CommunityFragment();  
	        break;  
	    case 4:  
	        fragment = new PagesFragment();  
	        break;  
	    case 5:  
	        fragment = new WhatsHotFragment();  
	        break;  
	    default:  
	        break;  
	    }  
	  
	    if (fragment != null) {  
	        FragmentManager fragmentManager = getFragmentManager();
	        fragmentManager.beginTransaction()  
	                .replace(R.id.content, fragment).commit();  
	        // update selected item and title, then close the drawer  
	        setTitle(title);
	        mSlidingMenu.showContent();
	    } else {  
	        // error in creating fragment  
	        Log.e("MainActivity", "Error in creating fragment");  
	    }  
	}
}


SlidingMenu 菜单Fragment

package com.example.slidingmenufragmenttest.fragment;

import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.slidingmenufragmenttest.R;
import com.example.slidingmenufragmenttest.adapter.NavDrawerListAdapter;
import com.example.slidingmenufragmenttest.entity.NavDrawerItem;

@SuppressLint("NewApi")
public class MenuFragment extends Fragment implements OnItemClickListener {

	private ListView mDrawerList;
	private String[] mNavMenuTitles;
	private TypedArray mNavMenuIconsTypeArray;
	private ArrayList<NavDrawerItem> mNavDrawerItems;
	private NavDrawerListAdapter mAdapter;
	private SLMenuListOnItemClickListener mCallback;
	private int selected = -1;

	@Override
	public void onAttach(Activity activity) {
		try {
			mCallback = (SLMenuListOnItemClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnResolveTelsCompletedListener");
		}
		super.onAttach(activity);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View rootView = inflater.inflate(R.layout.fragment_menu, null);
		
		findView(rootView);
		
		return rootView;
	}

	private void findView(View rootView) {
		
		mDrawerList = (ListView) rootView.findViewById(R.id.left_menu);  
		
		mNavMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);  
        // nav drawer icons from resources  
        mNavMenuIconsTypeArray = getResources()  
                    .obtainTypedArray(R.array.nav_drawer_icons);  
              
        mNavDrawerItems = new ArrayList<NavDrawerItem>();  
  
        // adding nav drawer items to array  
        // Home  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[0], mNavMenuIconsTypeArray  
                .getResourceId(0, -1)));  
        // Find People  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[1], mNavMenuIconsTypeArray  
                .getResourceId(1, -1)));  
        // Photos  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[2], mNavMenuIconsTypeArray  
                .getResourceId(2, -1)));  
        // Communities, Will add a counter here  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[3], mNavMenuIconsTypeArray  
                .getResourceId(3, -1), true, "22"));  
        // Pages  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[4], mNavMenuIconsTypeArray  
                .getResourceId(4, -1)));  
        // What's hot, We will add a counter here  
        mNavDrawerItems.add(new NavDrawerItem(mNavMenuTitles[5], mNavMenuIconsTypeArray  
                .getResourceId(5, -1), true, "50+"));  
  
        // Recycle the typed array  
        mNavMenuIconsTypeArray.recycle();  
          
        // setting the nav drawer list adapter  
        mAdapter = new NavDrawerListAdapter(getActivity(),  
                        mNavDrawerItems);  
        mDrawerList.setAdapter(mAdapter);  
        mDrawerList.setOnItemClickListener(this);  
        
        if(selected!=-1){
        	mDrawerList.setItemChecked(selected, true);  
            mDrawerList.setSelection(selected);  
        }else{
        	mDrawerList.setItemChecked(0, true);  
            mDrawerList.setSelection(0);  
        }
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		
		// update selected item and title, then close the drawer  
        mDrawerList.setItemChecked(position, true);  
        mDrawerList.setSelection(position);  
        
        if(mCallback!=null){
        	mCallback.selectItem(position, mNavMenuTitles[position]);
        }
        selected = position;
	}

	/**
     * 左侧菜单 点击回调接口
     * @author FX_SKY
     *
     */
    public interface SLMenuListOnItemClickListener{
    	
    	public void selectItem(int position,String title);
    }
}


内容Fragment

package com.example.slidingmenufragmenttest.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.slidingmenufragmenttest.R;

@SuppressLint("NewApi")
public class HomeFragment extends Fragment {
	
	public HomeFragment(){}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
         
        return rootView;
    }
}


SlidingMenu 菜单List 点击事件是通过回调接口在MainActivity中执行的

@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		
		// update selected item and title, then close the drawer  
        mDrawerList.setItemChecked(position, true);  
        mDrawerList.setSelection(position);  
        
        if(mCallback!=null){
        	mCallback.selectItem(position, mNavMenuTitles[position]);
        }
        selected = position;
	}

	/**
     * 左侧菜单 点击回调接口
     * @author FX_SKY
     *
     */
    public interface SLMenuListOnItemClickListener{
    	
    	public void selectItem(int position,String title);
    }


运行效果如下:

Android SlidingMenu 开源项目使用示例(一)_第1张图片



Android SlidingMenu 开源项目使用示例(一)_第2张图片



Demo下载地址:http://download.csdn.net/detail/fx_sky/6723039





你可能感兴趣的:(android,SlidingMenu)