1. 程式人生 > >SlidingMenu+Fragment實現側滑選單

SlidingMenu+Fragment實現側滑選單

實現SlidingMenu需要先匯入第三方slidingmenu.jar包。

複製  pan.baidu.com/s/1qW1525Q  到位址列。

主介面佈局

activity_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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/action_settings" />

</RelativeLayout>

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

</FrameLayout>

側滑選單佈局

sliding_menu.xml

<?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:background="#cccccc"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>

側滑選單操作類
MySlidingMenu.java

package com.example.slidingmenuactivity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MySlidingMenu extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.sliding_menu, null);
		return view;
	}
}

主介面實現類

MainActivity.java

package com.example.slidingmenuactivity;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.slidingmenu.lib.SlidingMenu;

public class MainActivity extends FragmentActivity {

	private Button button;// 點選展開側滑選單
	private SlidingMenu menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				menu.showMenu();
			}
		});
		initMenu();
	}

	public void initMenu() {
		// 初始化側滑選單
		menu = new SlidingMenu(this);
		menu.setMode(SlidingMenu.LEFT);// 設定左滑選單
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);// 設定滑動的螢幕範圍,該設定為全屏區域都可以滑動
		// menu.setShadowDrawable(R.drawable.shadow);// 設定陰影圖片
		// menu.setShadowWidthRes(R.dimen.shadow_width);// 設定陰影圖片的寬度
		// menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// SlidingMenu劃出時主頁面顯示的剩餘寬度
		menu.setBehindWidth(380);// 設定SlidingMenu選單的寬度
		menu.setFadeDegree(0.35f);// SlidingMenu滑動時的漸變程度
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);// 使SlidingMenu附加在Activity上
		menu.setMenu(R.layout.menu_frame);// 設定menu的佈局檔案

		// 得到transaction物件
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		//新增一個Fragment
		transaction.add(R.id.menu_frame, new MySlidingMenu());
		transaction.commit();
	}

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

}

SlidingMenu截圖

SlidingMenu簡介:
SlidingMenu的是一種比較新的設定介面或配置介面效果,在主介面左滑或者右滑出現設定介面,能方便的進行各種操作.目前有大量的應用都在使用這一效果。如Evernote、Google+、Foursquare等,國內的豌豆夾,人人,360手機助手等都使用SlidingMenu的介面方案。
 

專案下載地址:https://github.com/jfeinstein10/SlidingMenu
注意: SlidingMenu依賴於另一個開源專案ActionBarSherlock,所以需要將ActionBarSherlock新增作為SlidingMenu的庫工程,否則會報資源找不到錯誤。
然後再將SlidingMenu新增到自己的工程中去。
 
SlidingMenu整合常見錯誤:
Jar mismatch! Fix your dependencies :引用的工程和自身工程以來的jar包版本不一致導致的衝突。確保SlidingMenu和ActionBarSherLock所使用的jar包版本一致
 
如果使用到ActionBarSherLock的相關api,可能報找不到getSupportActionBar等ActionBarSherLock的方法。原因是使用ActionBarSherLock的Activity需繼承於SherlockActivity,修改SlidingMenu library中的SlidingFragmentActivity,讓它繼承於SherlockFragmentActivity,重新編譯library匯入。
 
SlidingMenu 常用屬性介紹:
menu.setMode(SlidingMenu.LEFT);//設定左滑選單
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//設定滑動的螢幕範圍,該設定為全屏區域都可以滑動
menu.setShadowDrawable(R.drawable.shadow);//設定陰影圖片
menu.setShadowWidthRes(R.dimen.shadow_width);//設定陰影圖片的寬度
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);//SlidingMenu劃出時主頁面顯示的剩餘寬度
menu.setBehindWidth(400);//設定SlidingMenu選單的寬度
menu.setFadeDegree(0.35f);//SlidingMenu滑動時的漸變程度
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);//使SlidingMenu附加在Activity上
menu.setMenu(R.layout.menu_layout);//設定menu的佈局檔案
menu.toggle();//動態判斷自動關閉或開啟SlidingMenu
menu.showMenu();//顯示SlidingMenu
menu.showContent();//顯示內容
menu.setOnOpenListener(onOpenListener);//監聽slidingmenu開啟
關於關閉menu有兩個監聽,簡單的來說,對於menu close事件,一個是when,一個是after
menu.OnClosedListener(OnClosedListener);//監聽slidingmenu關閉時事件
menu.OnClosedListener(OnClosedListener);//監聽slidingmenu關閉後事件
 
左右都可以劃出SlidingMenu菜單隻需要設定
menu.setMode(SlidingMenu.LEFT_RIGHT);屬性,然後設定右側選單的佈局檔案
menu.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
     
[java]
setBehindContentView(R.layout.menu_frame);  
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();  
leftMenuFragment = new MenuFragment();  
t.replace(R.id.menu_frame, leftMenuFragment);  
t.commit();  
 
MenuFragment其實就是一個Fragment,顯示一個ListView
然後點選ListView的每一項的時候,通知Activity切換不同的Fragment
為了看清效果,我們新建5個Frament,分別是
Fragment1, Fragment2, Fragment3, Fragment4, Fragment5
在SlidingMenu中用ListView顯示。
 
設定主頁面顯示的Fragment:
[java]  
if (savedInstanceState == null) {//== null的時候新建Fragment1  
contentFragment = new Fragment1();  
} else {//不等於null,直接get出來  
//不等於null,找出之前儲存的當前Activity顯示的Fragment  
contentFragment = getSupportFragmentManager().getFragment(savedInstanceState, "contentFragment");  
}  
//設定內容Fragment  
getSupportFragmentManager()  
.beginTransaction()  
.replace(R.id.content_frame, contentFragment)  
.commit();  
 
 
在Activity的onSaveInstanceState中儲存當前顯示的Fragment
getSupportFragmentManager().putFragment(outState, "contentFragment", contentFragment);
設定SlidingMenu屬性
sm = getSlidingMenu();
//如果只顯示左側選單就是用LEFT,右側就RIGHT,左右都支援就LEFT_RIGHT
sm.setMode(SlidingMenu.LEFT_RIGHT);//設定選單滑動模式,選單是出現在左側還是右側,還是左右兩側都有
sm.setShadowDrawable(R.drawable.shadow);//設定陰影的圖片資源
sm.setShadowWidthRes(R.dimen.shadow_width);//設定陰影圖片的寬度
//sm.setBehindWidth(200);//設定選單的寬
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);//SlidingMenu劃出時主頁面顯示的剩餘寬度
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//設定滑動的區域
 
支援右側劃出選單:
//SlidingMenu可以同時支援劃出左右兩側的選單,互不衝突,而且動畫優美,體驗良好。
sm.setSecondaryMenu(R.layout.menu_frame2);//設定右側選單
sm.setSecondaryShadowDrawable(R.drawable.shadowright);//設定右側選單陰影的圖片資源
//右側SlidingMenu的Fragment
 getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame2, new SampleListFragment()).commit();
 
設定ActionBar可以被點選:
getSupportActionBar().setHomeButtonEnabled(true);//actionbar主按鍵可以被點選
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//顯示向左的圖示
setSlidingActionBarEnabled(false);//左右兩側slidingmenu的fragment是否顯示標題欄
 
切換主頁面顯示的Fragment:
public void switchContent(Fragment f) {
//給內容Fragment賦值,並在onSaveInstanceState時儲存這個Fragment
contentFragment = f;
FragmentTransaction  t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.content_frame, f);
t.commit();
sm.showContent();
 
使用普通Activity實現SlidingMenu:
[java]  
slidingMenu menu = new SlidingMenu(this);//直接new,而不是getSlidingMenu  
menu.setMode(SlidingMenu.LEFT);  
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);  
menu.setShadowDrawable(R.drawable.shadow);  
menu.setShadowWidthRes(R.dimen.shadow_width);  
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);  
menu.setBehindWidth(400);//設定SlidingMenu選單的寬度  
menu.setFadeDegree(0.35f);  
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);//必須呼叫  
menu.setMenu(R.layout.menu_layout_left);//就是普通的layout佈局  
menu.setBehindCanvasTransformer(mTransformer);  
 
 
相應SlidingMenu裡的點選事件,因為SlidingMenu已經被包含在了Activity中了,所以直接findViewById(id),拿到view之後就可以進行相應的處理。
 
支援左右兩側都能劃出選單
menu.setSecondaryMenu(R.layout.menu_layout_right);
menu.setSecondaryShadowDrawable(R.drawable.shadowright);
 
右側選單一樣直接findViewById(id),拿到view之後就可以任意處理了
 
更換SlidingMenu的動畫
SlidingMenu支援左滑或者右滑時定義不同的動畫,包括拉伸,縮放,旋轉等動畫。就是在滑動的過程中,SlidingMenu如何出現的動畫。
動畫使用也很簡單
首先定義CanvasTransformer mTransformer;變數:
[java]  
mTransformer = new CanvasTransformer() {  
@Override  
public void transformCanvas(Canvas canvas, float percentOpen) {  
float scale = (float) (percentOpen*0.25 + 0.75);  
canvas.scale(scale, scale, canvas.getWidth()/2, canvas.getHeight()/2);  
}  
};  
 
然後將mTransformer物件設定給SlidingMenu即可,這個是縮放動畫:
[java]  
private void initSlidUpCanvasTransformer() {  
mTransformer = new CanvasTransformer() {  
 
@Override  
public void transformCanvas(Canvas canvas, float percentOpen) {  
canvas.translate(0, canvas.getHeight()*(1-interp.getInterpolation(percentOpen)));  
}  
};  
}  
 
private static Interpolator interp = new Interpolator() {  
@Override  
public float getInterpolation(float t) {  
t -= 1.0f;  
return t * t * t + 1.0f;  
}  
};  
 
拉伸動畫:
[java]  
mTransformer = new CanvasTransformer() {  
@Override  
public void transformCanvas(Canvas canvas, float percentOpen) {  
canvas.scale(percentOpen, 1, 0, 0);  
}  
});