首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下)

2013-11-04 
【android开发】滑动菜单栏(开源项目SlidingMenu的示例)( 下)上一篇文章对SlidingMenu库详细介绍了一下,这一

【android开发】滑动菜单栏(开源项目SlidingMenu的示例)( 下)

上一篇文章对SlidingMenu库详细介绍了一下,这一一篇我就用一个实例,具体来看看如何去实现一个滑动效果的菜单栏。这个实例之前也是从网上看到,一位同事对这个实例精简了一下,感觉不错给我,我又对这个实例进行了一下自己的修改,应该是一个比较好的框架了,以后用到了,就可以直接填写代码就行了。在文章的最后,我也会把这个实例的代码下载链接告诉大家,以便给需要的朋友。那就先来看看效果图吧:

                          主界面菜单                                                                                   右菜单                                                                           

【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下)                                   【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下) 

                        左菜单

 【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下)

这个界面是不是很漂亮?我是这么感觉,不知道朋友们怎么认为,那么我们现在就看看如何去一步一步的实现这个效果吧!

上一篇我们已经告诉大家了,新建一个项目,首先要把SlidingMenu库添加eclipse中,再导进项目中,具体操作可以参看上一篇文章。

先看一下项目的目录结构:

【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下)        【android开发】滑动菜单栏(开源项目SlidingMenu的示范)( 下)


一、我们先看一下布局文件:

和以往不同的是,我们需要建几个FrameLayout布局文件,主要是为了定义虚拟的视图,方便Fragment能够替换该视图,以达到Fragment的视图内容能够显示在屏幕上的效果。

主界面虚拟视图slidingmenu_content.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/slidingmenu_content"    android:layout_width="match_parent"    android:layout_height="match_parent" />
左菜单虚拟视图slidingmenu_menu.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/slidingmenu_menu"    android:layout_width="match_parent"    android:layout_height="match_parent" />
右菜单虚拟视图slidingmenu_menu_2.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/slidingmenu_menu_2"    android:layout_width="match_parent"    android:layout_height="match_parent" />
主界面初始化视图文件slidingmenu_main.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/slidingmenu_main_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" ></LinearLayout>
主界面视图文件my_main.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@drawable/my_bg">        <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:paddingLeft="12dp"        android:paddingRight="12dp"        android:paddingTop="15dp"        android:gravity="center_vertical"        android:visibility="gone">        <LinearLayout            android:id="@+id/layout_search_type"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:gravity="center_vertical"        android:padding="5dp"        android:background="@drawable/ic_bg_for_dropdown">            <TextView                 android:id="@+id/tv_search_type"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="出  售"/>            <ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"            android:layout_marginLeft="2dp"android:src="@drawable/ic_expansion"/>        </LinearLayout>        <EditText             android:id="@+id/edt_search"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:singleLine="true"            android:background="@drawable/ic_bg_for_edit"/>        <Button             android:id="@+id/btn_search"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:minWidth="48dp"            android:text="搜索"            android:background="@drawable/ic_bg_for_btn"/>    </LinearLayout>    <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"    android:gravity="center">    <ScrollView          android:id="@+id/scrollview"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1">    <LinearLayout         android:id="@+id/layout_classify"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical"    android:gravity="center"></LinearLayout></ScrollView></LinearLayout>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:paddingBottom="15dp"        android:paddingLeft="15dp"        android:paddingRight="15dp">        <ImageView            android:id="@+id/btn_more"            android:layout_width="32dp"            android:layout_height="32dp"            android:layout_alignParentLeft="true"            android:clickable="true"            android:focusable="true"            android:scaleType="fitXY"            android:src="@drawable/ic_btn_more"         android:background="@drawable/my_bg_for_imgbtn"/>        <ImageView            android:id="@+id/btn_select_city"            android:layout_width="32dp"            android:layout_height="32dp"            android:layout_alignParentRight="true"            android:clickable="true"            android:focusable="true"            android:scaleType="fitXY"            android:src="@drawable/ic_btn_select_city"         android:background="@drawable/my_bg_for_imgbtn"/>    </RelativeLayout></LinearLayout>
存放主界面资源视图文件my_main_inner_grid.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:background="@drawable/ic_pic__box" >    <ImageView        android:id="@+id/inner_img"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:scaleType="fitXY"        android:src="@drawable/my_bg_focus_for_classify" />    <TextView        android:id="@+id/txt_tile"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/inner_img"        android:layout_centerHorizontal="true"        android:layout_marginBottom="4dp"        android:textColor="#ffffff" /></RelativeLayout>
左菜单视图文件my_main_left.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:background="@drawable/my_bg_for_more"    android:orientation="vertical" >    <LinearLayout        style="@style/title_bar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:minHeight="50dp" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="系统菜单"            android:textColor="#ffffff"            android:textSize="25dp" />    </LinearLayout>    <LinearLayout        android:id="@+id/layout_mortgage_calculator"        style="@style/list_item_01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:layout_weight="1"            android:text="登录" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/ic_right_to" />    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="2dp"        android:layout_marginRight="4dp"        android:background="@drawable/ic_line" />    <!-- 意见反馈 -->    <LinearLayout        android:id="@+id/layout_feedback"        style="@style/list_item_01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:layout_weight="1"            android:text="下载离线盘点数据" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/ic_right_to" />    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="2dp"        android:layout_marginRight="4dp"        android:background="@drawable/ic_line" />    <!-- 关于我们 -->    <LinearLayout        android:id="@+id/layout_about_us"        style="@style/list_item_01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:layout_weight="1"            android:text="系统设置" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/ic_right_to" />    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="2dp"        android:layout_marginRight="4dp"        android:background="@drawable/ic_line" />    <!-- 检查更新 -->    <LinearLayout        android:id="@+id/layout_check_for_updates"        style="@style/list_item_01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:layout_weight="1"            android:text="修改用户密码" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/ic_right_to" />    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="2dp"        android:layout_marginRight="4dp"        android:background="@drawable/ic_line" />    <LinearLayout        android:id="@+id/layout_out"        style="@style/list_item_01"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:layout_weight="1"            android:text="退出" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/ic_right_to" />    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="2dp"        android:layout_marginRight="4dp"        android:background="@drawable/ic_line" /></LinearLayout>
右菜单视图文件my_main_right.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical"    android:background="@drawable/my_bg_for_more"><LinearLayout    style="@style/title_bar"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:gravity="center">    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/txt_city_switch"        android:textSize="24sp"        android:textStyle="bold"        android:textColor="@android:color/white"/></LinearLayout><ListView     android:id="@+id/list"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="3dp"    android:fadingEdge="none"     android:transcriptMode="disabled"     android:cacheColorHint="@null"     android:divider="@drawable/ic_line"/></LinearLayout>
右菜单存放资源视图文件my_main_inner_list_for_cities.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    style="@style/list_item_for_city"    android:orientation="horizontal"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center_vertical">    <TextView         android:id="@+id/inner_title"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_weight="1"    android:layout_marginLeft="8dp"/><ImageView     android:id="@+id/inner_img"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_marginRight="8dp"/>    </LinearLayout>

为了使界面效果更加漂亮,我们再添加一个用于显示阴影效果的文件slidingmenu_shadow.xml和slidingmenu_shadow2.xml:代码如下:

package com.gtf.test.buildin;import android.content.Context;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.View;import android.widget.TextView;import com.gtf.test.utils.ActivityUtils;/*  *Fragment作为Activity界面的一部分组成出现 *可以在一个Activity中同时出现多个Fragment,并且,一个Fragment亦可在多个Activity中使用。 *在Activity运行过程中,可以添加、移除或者替换Fragment(add()、remove()、replace()) *Fragment可以响应自己的输入事件,并且有自己的生命周期,当然,它们的生命周期直接被其所属的 *宿主activity的生命周期影响。 * 可以 * */public class BaseFragment extends Fragment implements View.OnClickListener{public Context context;@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);this.context = this.getActivity();}@Overridepublic void onClick(View v) {// TODO Auto-generated method stub}public void exit(){this.getActivity().finish();}public void exitToHome(){ActivityUtils.finishAll();}public static final void setTextStyle(TextView view, boolean bold){view.getPaint().setFakeBoldText(bold);}}
建一个所有界面之间的操作的ActivityUtils类,代码如下:

package com.gtf.test.utils;import java.text.DecimalFormat;import java.text.ParseException;import java.util.ArrayList;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Parcelable;import com.gtf.test.act.MainAct;/** * 所有界面之间的操作,都放这里 * @author liudongqiu * */public class ActivityUtils {private static ArrayList<Activity> actList = new ArrayList<Activity>();public static final void addAct(Activity act){actList.add(act);}public static final void finishAll(){for(int i=actList.size()-1; i>=0; i--){actList.get(i).finish();}actList.clear();}public static final void clearAll(){actList.clear();}public static final void toHomeAct(Context context){to(context, MainAct.class);}public static final void to(Context context, Class<?> cls){to(context, cls, null);}public static final void to(Context context, Class<?> cls, Bundle data){Intent intent = new Intent(context, cls);if(data != null){intent.putExtras(data);}context.startActivity(intent);}public static final void gotoHome(Context context){Intent intent = new Intent(Intent.ACTION_MAIN);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.addCategory(Intent.CATEGORY_HOME);context.startActivity(intent);}/** * 添加桌面快捷图标 * 需要权限: * <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> * @param context * @param cls *//*public static void createShorcut(Context context, int logo, String name, Class<?> cls) {    Intent thisIntent = new Intent();    thisIntent.setClass(context, cls);    String ACTION_ADD_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";    Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);    Parcelable icon = Intent.ShortcutIconResource.fromContext(context, logo);    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, thisIntent);    context.sendBroadcast(addShortcut);}*/public static final DecimalFormat format = new DecimalFormat("0.00");/** * 保留两位小数 * @param decimal * @return */public static final String formatToTwoDecimalPlaces(String decimal){try {return format.format(format.parse(decimal));} catch (ParseException e) {return decimal;}}public static final String formatToDate(String date){if(date == null){return "";}else{int index = date.indexOf(" ");return (index > 0 ? date.substring(0, index) : date).replaceAll("/", "-");}}}
建一个操作所有提示功能的WarnUtils类,代码如下:

package com.gtf.test.utils;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.widget.Toast;/** * 所有提示都放到这里 * @author liudongqiu * */public class WarnUtils {public static final void showDialog(Context context, String text){new AlertDialog.Builder(context).setMessage(text).setNegativeButton("关闭", null).create().show();}public interface OnClickListener extends DialogInterface.OnClickListener {}public static final void toast(Context context, int textId){toast(context, context.getResources().getString(textId));}public static final void toast(Context context, String text){Toast.makeText(context, text, Toast.LENGTH_SHORT).show();}}
建一个用于处理主界面事件的MainFragment类,这个继承基类BaseFragment,代码如下:

package com.gtf.test.act;import java.util.ArrayList;import android.content.Context;import android.os.Bundle;import android.util.DisplayMetrics;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import com.gtf.test.R;import com.gtf.test.buildin.BaseFragment;import com.gtf.test.utils.ActivityUtils;import com.lxh.slidingmenu.lib.SlidingMenu;public class MainFragment extends BaseFragment {public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.my_main, null);}private SlidingMenu menu;private LinearLayout layoutSearchType;private Button btnSearch;private ImageView ivMore;private ImageView ivSelectCity;public MainFragment(SlidingMenu menu) {this.menu = menu;}public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);this.initViews();}private void initViews() {View parent = this.getView();this.layoutSearchType = (LinearLayout) parent.findViewById(R.id.layout_search_type);this.btnSearch = (Button) parent.findViewById(R.id.btn_search);this.ivMore = (ImageView) parent.findViewById(R.id.btn_more);this.ivSelectCity = (ImageView) parent.findViewById(R.id.btn_select_city);this.layoutSearchType.setOnClickListener(this);this.btnSearch.setOnClickListener(this);this.ivMore.setOnClickListener(this);this.ivSelectCity.setOnClickListener(this);DisplayMetrics dm = new DisplayMetrics();this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);int screenWidth = dm.widthPixels;int offsetX = (int) (12 * dm.density);int spacing = (int) (8 * dm.density);int itemWidth = (screenWidth - 3 * offsetX) / 2;int itemHeight = (int) (112.5f * itemWidth / 142.5f);MyAdapter adapter = new MyAdapter(context, getDataList());LinearLayout classifyLayout = (LinearLayout) parent.findViewById(R.id.layout_classify);classifyLayout.setPadding(offsetX, offsetX - spacing, offsetX, offsetX);LinearLayout row = null;View view;LinearLayout.LayoutParams layoutParams;for (int i = 0; i < adapter.getCount(); i++) {layoutParams = new LinearLayout.LayoutParams(itemWidth, itemHeight);if (i % 2 == 0) {row = new LinearLayout(context);row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1));classifyLayout.addView(row);} else {layoutParams.leftMargin = spacing;}view = adapter.getView(i, null, null);layoutParams.topMargin = spacing;row.addView(view, layoutParams);}}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_more: {this.menu.showMenu();break;}case R.id.btn_select_city: {this.menu.showSecondaryMenu();break;}}}private class MyAdapter extends BaseAdapter {private Context context;private ArrayList<MyData> datas;private LayoutInflater inflater;public MyAdapter(Context context, ArrayList<MyData> datas) {this.context = context;this.datas = datas;if (this.datas == null) {this.datas = new ArrayList<MyData>();}this.inflater = LayoutInflater.from(this.context);}@Overridepublic int getCount() {return this.datas.size();}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {MyHolder holder;if (convertView == null) {convertView = inflater.inflate(R.layout.my_main_inner_grid, null);holder = new MyHolder();holder.img = (ImageView) convertView.findViewById(R.id.inner_img);holder.txt = (TextView) convertView.findViewById(R.id.txt_tile);holder.img.setOnClickListener(this.clickListener);// holder.img.setOnTouchListener(this.touchListener);convertView.setTag(holder);} else {holder = (MyHolder) convertView.getTag();}MyData data = this.datas.get(position);holder.data = data;holder.img.setBackgroundResource(data.rid);holder.txt.setText(data.name);holder.img.setTag(holder);return convertView;}private View.OnClickListener clickListener = new View.OnClickListener() {@Overridepublic void onClick(View v) {((MyHolder) v.getTag()).data.type.toAct(context);}};private View.OnTouchListener touchListener = new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubreturn false;}};}private class MyHolder {ImageView img;TextView txt;MyData data;}private static enum MyClassify {Recommend, MyCenter, Sell, Rent, SchoolDistrictRoom, ResidentialHousing;public void toAct(Context context) {switch (this) {case Recommend:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;case MyCenter:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;case Sell:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;case Rent:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;case SchoolDistrictRoom:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;case ResidentialHousing:Toast.makeText(context, "代开发中.......", Toast.LENGTH_LONG).show();break;}}}private static class MyData {private int rid;private int name;private MyClassify type;public MyData(int rid, int name, MyClassify type) {this.rid = rid;this.name = name;this.type = type;}}private static final ArrayList<MyData> getDataList() {ArrayList<MyData> list = new ArrayList<MyData>();list.add(new MyData(R.drawable.ic_pic_recommend, R.string.txt_recommend, MyClassify.Recommend));list.add(new MyData(R.drawable.ic_pic_my_center, R.string.txt_my_center, MyClassify.MyCenter));list.add(new MyData(R.drawable.ic_pic_sell, R.string.txt_sell, MyClassify.Sell));list.add(new MyData(R.drawable.ic_pic_rent, R.string.txt_rent, MyClassify.Rent));list.add(new MyData(R.drawable.ic_pic_school_district_room, R.string.txt_school_district_room, MyClassify.SchoolDistrictRoom));list.add(new MyData(R.drawable.ic_pic_residential_housing, R.string.txt_residential_housing, MyClassify.ResidentialHousing));return list;}}
同样建议两个类分别处理左右菜单事件,MainLeftFragment类和MainRightFragment类,同样继承基类BaseFragment,代码如下:

package com.gtf.test.act;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.LinearLayout;import com.gtf.test.R;import com.gtf.test.buildin.BaseFragment;import com.gtf.test.utils.WarnUtils;public class MainLeftFragment extends BaseFragment {public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.my_main_left, null);}private LinearLayout layoutMortgageCalculator;private LinearLayout layoutFeedback;private LinearLayout layoutAboutUs;private LinearLayout layoutCheckForUpdates;private LinearLayout layout_out;public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);this.initViews();}private void initViews() {View parent = this.getView();this.layoutMortgageCalculator = (LinearLayout) parent.findViewById(R.id.layout_mortgage_calculator);this.layoutFeedback = (LinearLayout) parent.findViewById(R.id.layout_feedback);this.layoutAboutUs = (LinearLayout) parent.findViewById(R.id.layout_about_us);this.layoutCheckForUpdates = (LinearLayout) parent.findViewById(R.id.layout_check_for_updates);this.layout_out = (LinearLayout) parent.findViewById(R.id.layout_out);this.layoutMortgageCalculator.setOnClickListener(this);this.layoutFeedback.setOnClickListener(this);this.layoutAboutUs.setOnClickListener(this);this.layoutCheckForUpdates.setOnClickListener(this);this.layout_out.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.layout_mortgage_calculator: {WarnUtils.toast(this.context, "登录");break;}case R.id.layout_feedback: {WarnUtils.toast(this.context, "下载离线盘点数据");break;}case R.id.layout_about_us: {WarnUtils.toast(this.context, "系统设置");break;}case R.id.layout_check_for_updates: {WarnUtils.toast(this.context, "修改用户密码");break;}case R.id.layout_out: {WarnUtils.toast(this.context, "退出");break;}}}}
package com.gtf.test.act;import java.util.ArrayList;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import com.gtf.test.R;import com.gtf.test.buildin.BaseFragment;import com.lxh.slidingmenu.lib.SlidingMenu;public class MainRightFragment extends BaseFragment implements AdapterView.OnItemClickListener{public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.my_main_right, null);}private SlidingMenu menu;private ListView listView;private MyAdapter adapter;public MainRightFragment(SlidingMenu menu){this.menu = menu;}public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);this.initViews();}private void initViews(){View parent = this.getView();this.adapter = new MyAdapter(context, this.getCities());this.listView = (ListView)parent.findViewById(R.id.list);this.listView.setAdapter(this.adapter);//this.listView.setOnItemClickListener(this);}@Overridepublic void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {MyHolder holder = (MyHolder)convertView.getTag();holder.city.selected = true;//holder.img.setImageResource(R.drawable.ic_select_normal);MyHolder oldHolder = this.adapter.getSelectedHolder();if(oldHolder != null){if(oldHolder.city.selected){//oldHolder.img.setImageResource(R.drawable.ic_select_empty);oldHolder.city.selected = false;}}this.adapter.setSelectedHolder(holder);this.adapter.notifyDataSetChanged();// TODO 这里还要做其它的事情this.menu.toggle();}private class City{private String cityName;private String webUrl;private boolean selected;private City(String cityName, String webUrl){this.cityName = cityName;this.webUrl = webUrl;}private City(String cityName, String webUrl, boolean selected){this.cityName = cityName;this.webUrl = webUrl;this.selected = selected;}}private class MyHolder{private TextView title;private ImageView img;private City city;}private class MyAdapter extends BaseAdapter{private MyHolder selectedHolder;private Context context;private ArrayList<City> cities;private LayoutInflater inflater;private MyAdapter(Context context, ArrayList<City> cities){this.context = context;this.cities = cities;if(this.cities == null){this.cities = new ArrayList<City>();}this.inflater = LayoutInflater.from(this.context);}@Overridepublic int getCount() {return this.cities.size();}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {MyHolder holder;if(convertView == null){convertView = this.inflater.inflate(R.layout.my_main_inner_list_for_cities, null);holder = new MyHolder();holder.title = (TextView)convertView.findViewById(R.id.inner_title);holder.img = (ImageView)convertView.findViewById(R.id.inner_img);convertView.setTag(holder);convertView.setOnTouchListener(onTouchListener);convertView.setOnClickListener(onClickListener);}else{holder = (MyHolder)convertView.getTag();}City city = this.cities.get(position);holder.title.setText(city.cityName);if(city.selected){holder.img.setImageResource(R.drawable.ic_select_normal);selectedHolder = holder;}else{holder.img.setImageResource(R.drawable.ic_select_empty);}holder.city = city;return convertView;}private void setSelectedHolder(MyHolder selectedHolder){this.selectedHolder = selectedHolder;}private MyHolder getSelectedHolder(){return this.selectedHolder;}private View.OnClickListener onClickListener = new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubMyHolder holder = (MyHolder)v.getTag();holder.city.selected = true;holder.img.setImageResource(R.drawable.ic_select_normal);MyHolder oldHolder = getSelectedHolder();if(oldHolder != null && holder != oldHolder){if(oldHolder.city.selected){oldHolder.img.setImageResource(R.drawable.ic_select_empty);oldHolder.city.selected = false;}}setSelectedHolder(holder);//this.notifyDataSetChanged();// TODO 这里还要做其它的事情menu.toggle();}};private View.OnTouchListener onTouchListener = new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:if(event.getPointerCount() == 1){((MyHolder)v.getTag()).img.setImageResource(R.drawable.ic_select_pressed);}break;case MotionEvent.ACTION_CANCEL:case MotionEvent.ACTION_UP:case MotionEvent.ACTION_MASK:if(event.getPointerCount() == 1){MyHolder holder = (MyHolder)v.getTag();if(holder.city.selected){holder.img.setImageResource(R.drawable.ic_select_normal);}else{holder.img.setImageResource(R.drawable.ic_select_empty);}}}return false;}};}public ArrayList<City> getCities(){ArrayList<City> list = new ArrayList<City>();list.add(new City("莞城区", "", true));list.add(new City("东城区", ""));list.add(new City("南城区", ""));list.add(new City("万江区", ""));list.add(new City("石碣区", ""));list.add(new City("石龙镇", ""));list.add(new City("茶山镇", ""));list.add(new City("石排镇", ""));list.add(new City("企石镇", ""));list.add(new City("横沥镇", ""));return list;}}
到这里对处理每一个菜单的类都已经建好了,下面就是在主activity类中去实现滑动菜单和对左右菜单调用了,主类MainAct,代码如下:

package com.gtf.test.act;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.util.DisplayMetrics;import android.view.KeyEvent;import com.gtf.test.R;import com.gtf.test.utils.ActivityUtils;import com.gtf.test.utils.WarnUtils;import com.lxh.slidingmenu.lib.SlidingMenu;public class MainAct extends FragmentActivity {private SlidingMenu menu;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.slidingmenu_main);                menu = new SlidingMenu(this);menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);menu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);menu.setShadowDrawable(R.drawable.slidingmenu_shadow);menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);menu.setFadeDegree(0.35f);menu.setBehindOffset(dm.widthPixels*50/100);menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);menu.setMode(SlidingMenu.LEFT_RIGHT);//这里模式设置为左右都有菜单,RIGHT显示右菜单,LEFT显示左菜单,LEFT_RIGH显示左右菜单menu.setContent(R.layout.slidingmenu_content);menu.setMenu(R.layout.slidingmenu_menu);menu.setSecondaryMenu(R.layout.slidingmenu_menu_2);menu.setSecondaryShadowDrawable(R.drawable.slidingmenu_shadow_2);getSupportFragmentManager().beginTransaction().replace(R.id.slidingmenu_content, new MainFragment(menu)).commit();//设置主页面内容getSupportFragmentManager().beginTransaction().replace(R.id.slidingmenu_menu, new MainLeftFragment()).commit();//设置左菜单内容getSupportFragmentManager().beginTransaction().replace(R.id.slidingmenu_menu_2, new MainRightFragment(menu)).commit();//设置右菜单内容           }    @Override    protected void onResume() {    super.onResume();    ActivityUtils.clearAll();    }        private long currentTime;@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {if(System.currentTimeMillis() - currentTime < 2000){this.finish();}else{WarnUtils.toast(this, R.string.warn_wether_to_exit);}currentTime = System.currentTimeMillis();return true;}return false;}}
大功告成了,主要的核心代码已经建好了,框架的搭建就是这样,漂亮的滑动效果就会出现了,当然了,只写上面的代码你的项目还是不会跑起来的,需要的资源图片和一些自定义的效果文件,还需要我们自己完成(特别注意:大家运行项目的时候千万别忘了导入slidingmenu_library项目,使用方法请参照上一篇文章)。滑动菜单栏的实现步骤就是这样了,结合两篇文章,相信很容易看懂这个原理。好了,滑动菜单栏到此就算结束了,接下来会继续给大家分享其他的有关技术,感谢大家的关注,请多支持!


滑动菜单栏(开源项目SlidingMenu的示例)


热点排行