Android SlidingMenu 布局实现

最近项目中用到了SlidingMenu 布局效果,在网上搜索了不少资料才实现了这个布局效果,项目中用到了 github上的一个开源项目 ,项目地址:https://github.com/jfeinstein10/SlidingMenu。兼容android 2.1以上所有版本。


工程项目结构如下图所示



它引用了一个 库项目 SlidingMenu 




MainActivity.java

package com.yulore.sdktest;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

import com.example.yulore_sdktest.R;
import com.slidingmenu.lib.SlidingMenu;
import com.yulore.sdktest.fragment.ContentFragment;
import com.yulore.sdktest.fragment.ContentFragment.OnMenuClickedListener;
import com.yulore.sdktest.fragment.MenuFragment;
import com.yulore.sdktest.fragment.MenuFragment.OnCityListSelectedListener;

public class MainActivity extends FragmentActivity implements OnCityListSelectedListener,OnMenuClickedListener{

    private SlidingMenu menu;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //1、设置全屏可以使用如下代码: 
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        //2、设置无title bar可以使用如下代码: 
//      requestWindowFeature(Window.FEATURE_NO_TITLE); 
        
        setTitle(R.string.app_name);
        // set the content view
        setContentView(R.layout.frame_content);
        
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        MenuFragment menuFragment = new MenuFragment();
        fragmentTransaction.replace(R.id.menu, menuFragment);
        fragmentTransaction.replace(R.id.content, new ContentFragment());
        fragmentTransaction.commit();
        
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.RIGHT);	//设置菜单 滑动模式,左滑还是右滑
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setShadowWidthRes(R.dimen.slidingmenu_shadowWidth);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_behindOffset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.frame_menu);
    }

	@Override
	public void onCityListSelected(int position) {

        ContentFragment contentFrag = (ContentFragment)
                getSupportFragmentManager().findFragmentById(R.id.content);

        if (contentFrag != null) {
            
        	contentFrag.updateContentView(position);
        } else {
        	ContentFragment newFragment = new ContentFragment();
            Bundle args = new Bundle();
            args.putInt(ContentFragment.CITY_LIST_POSITION, position);
            newFragment.setArguments(args);
        
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.content, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
        //显示 主界面
        menu.showContent();
    }

	/**
	 * 显示或隐藏菜单
	 */
	@Override
	public void onMenuButtonClicked() {
		
		Log.i("MainActivity", "onMenuButtonClicked invoke...");
		
		if(menu.isMenuShowing()){
			menu.showContent();
		}else{
			menu.showMenu();
		}
	}
}


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


右侧菜单 MenuFragment.java

package com.yulore.sdktest.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.yulore_sdktest.R;

public class MenuFragment extends ListFragment {
	
	OnCityListSelectedListener mCallback;
	
	public static String[] CITYLIST = {"北京","上海","广州","深圳","武汉","南京","苏州","杭州","天津","福州","厦门"};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setListAdapter(new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, CITYLIST));
	}

    // Container Activity must implement this interface
    public interface OnCityListSelectedListener {
        public void onCityListSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnCityListSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    
    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.menu) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

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

	public void onListItemClick(ListView parent, View v, int position, long id) {
		// Send the event to the host activity
        mCallback.onCityListSelected(position);
     // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
		Toast.makeText(getActivity(),
				"You have selected " + CITYLIST[position], Toast.LENGTH_SHORT).show();
	}

}


content_fragment_layout.xml

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

    <Button
        android:id="@+id/bt_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show_menu"
        android:textSize="20sp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"/>
    
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_centerInParent="true" />

</RelativeLayout>


内容显示 ContentFragment.java

package com.yulore.sdktest.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.yulore_sdktest.R;

public class ContentFragment extends Fragment implements OnClickListener {

	public final static String CITY_LIST_POSITION = "position";
	int mCurrentPosition = -1;
	OnMenuClickedListener mCallback;
	
	// Container Activity must implement this interface
    public interface OnMenuClickedListener {
        public void onMenuButtonClicked();
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnMenuClickedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnMenuButtonClickedListener");
        }
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (savedInstanceState != null) {
			mCurrentPosition = savedInstanceState.getInt(CITY_LIST_POSITION);
		}
		View view = inflater.inflate(R.layout.content_fragment_layout, null);
		
		Button bt_menu = (Button) view.findViewById(R.id.bt_menu);
		bt_menu.setOnClickListener(this);
		return view;
	}

	@Override
	public void onStart() {
		super.onStart();

		Bundle args = getArguments();
		if (args != null) {
			// Set article based on argument passed in
			updateContentView(args.getInt(CITY_LIST_POSITION));
		} else if (mCurrentPosition != -1) {
			updateContentView(mCurrentPosition);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// Save the current article selection in case we need to recreate the
		// fragment
		outState.putInt(CITY_LIST_POSITION, mCurrentPosition);
	}

	public void updateContentView(int position) {
		TextView article = (TextView) getActivity()
				.findViewById(R.id.tv_result);
		article.setText(MenuFragment.CITYLIST[position]);
		mCurrentPosition = position;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_menu:
			Log.i("ContentFragment", "点击了 菜单");
			mCallback.onMenuButtonClicked();
			break;

		default:
			break;
		}
	}

}


运行效果图




工程下载地址:http://download.csdn.net/detail/fx_sky/5518429





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值