首页 > 代码库 > Android编程心得-使用ActionBar+Fragment+ViewPager实现动态切换Menu效果

Android编程心得-使用ActionBar+Fragment+ViewPager实现动态切换Menu效果

1.首先上效果图




2.本例实现的效果主要适用于当前页面有多个页签时,进行Fragment切换时,可以利用不同的Menu样式与当前Fragment中的内容进行配合,可以大大增加复用性,看到效果图后,下面我来介绍我实现这一效果的主要步骤

2.1  因为此处我有3个样式,那么我需要在res/menu 文件夹下创建三个文件,style1.xml,style2.xml,style3.xml.这里我以style1.xml为例,具体的文字图标文件可按照需求,style2.xml,style3.xml类似。

style1.xml 源码如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_item1"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
      android:icon="@drawable/ic_menu_discard"
        android:title="@string/style1"/>

</menu>



2.2  在res/layout 文件下 分别创建activity 与fragment的对应视图文件,我拿Activity与其中一个Fragment举例,剩下的大家可以举一反三

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

 
        <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" >
    </android.support.v4.view.ViewPager>
    
</RelativeLayout>

fragment_first源码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

	<TextView 
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="第一个Fragment"
	    />

</RelativeLayout>

2.3 接下来就是逻辑实现了,按照效果我需要创建一个主逻辑Activity与三个Fragment逻辑文件,这里我同样只拿一个Fragment举例,剩下两个类似

FirstFragment源码:

package com.yqc.menuswitchdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View rootView = inflater.inflate(R.layout.fragment_first, container,
				false);

		return rootView;
	}
	

}


其中,在使用Fragment时需要一个自定义适配器,源码如下:

package com.yqc.menuswitchdemo;



import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class LFFragmentPagerAdapter extends FragmentPagerAdapter {
	Fragment[] fragmentArray;
	
	public LFFragmentPagerAdapter(FragmentManager fm,Fragment[] fragmentArray2) {
		super(fm);
		// TODO Auto-generated constructor stub
		if (null == fragmentArray2) {
			this.fragmentArray = new Fragment[] {};
		} else {
			this.fragmentArray = fragmentArray2;
		}
	}

	
	@Override
	public Fragment getItem(int arg0) {
		// TODO Auto-generated method stub
		return fragmentArray[arg0];
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return fragmentArray.length;
	}

}



最后,MainActivity源码:

package com.yqc.menuswitchdemo;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * @author YangQiCong 杨奇聪 QQ群 90733929 欢迎交流
 */
public class MainActivity extends FragmentActivity {

	private ViewPager viewPager;
	private ActionBar actionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		Fragment fragment1 = new FirstFragment();
		Fragment fragment2 = new SecondFragment();
		Fragment fragment3 = new ThirdFragment();
		Fragment[] fragmentArray = new Fragment[] { fragment1, fragment2,
				fragment3 };
		LFFragmentPagerAdapter adapter = new LFFragmentPagerAdapter(
				getSupportFragmentManager(), fragmentArray);

		viewPager.setAdapter(adapter);
		viewPager.setOffscreenPageLimit(3);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				System.out.println("arg0:" + arg0);
				actionBar.setSelectedNavigationItem(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		actionBar = getActionBar();
		// 设置ActionBar 的导航方式: Tab导航
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// actionBar.get

		Tab tab1 = actionBar.newTab().setText("页签1")
				.setIcon(android.R.drawable.ic_menu_agenda)
				.setTabListener(new ActionTabListener(fragment1));

		Tab tab2 = actionBar.newTab().setText("页签2")
				.setIcon(android.R.drawable.ic_menu_agenda)
				.setTabListener(new ActionTabListener(fragment2));

		Tab tab3 = actionBar.newTab().setText("页签3")
				.setIcon(android.R.drawable.ic_menu_agenda)
				.setTabListener(new ActionTabListener(fragment3));

		actionBar.addTab(tab1);
		actionBar.addTab(tab2);
		actionBar.addTab(tab3);

	}

	class ActionTabListener implements ActionBar.TabListener {

		// 声明Fragment

		private Fragment fragment;

		// 通过构造引用对应的Fragment

		public ActionTabListener(Fragment fragment) {
			this.fragment = fragment;
		}

		@Override
		public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			// ft.add(android.R.id.content, fragment, null);
			mType = tab.getPosition();
			System.out.println("tab.getPosition():" + tab.getPosition());
			viewPager.setCurrentItem(tab.getPosition());
			invalidateOptionsMenu();
		}

		@Override
		public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.style1, menu);
		return true;
	}

	private int mType;

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		System.out.println("当前mType:" + mType);
		menu.clear();
		MenuInflater inflater = this.getMenuInflater();
		switch (mType) {
		case 0:
			inflater.inflate(R.menu.style1, menu);
			break;

		case 1:
			inflater.inflate(R.menu.style2, menu);
			break;

		case 2:
			inflater.inflate(R.menu.style3, menu);
			break;
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_item1:
			Toast.makeText(this, "点击了第一个按钮", Toast.LENGTH_SHORT).show();
			break;
		case R.id.action_item2:
			Toast.makeText(this, "点击了第二个按钮", Toast.LENGTH_SHORT).show();
			break;
		case R.id.action_item3:
			Toast.makeText(this, "点击了第三个按钮", Toast.LENGTH_SHORT).show();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

}


3. 需要注意的是MainActivity主逻辑中我的mType是一个标识量,用于标识当前Fragment然后切换,如果有疑问欢迎大家一起交流

本例的全部源代码点击这里,转载请注明出处,谢谢!




Android编程心得-使用ActionBar+Fragment+ViewPager实现动态切换Menu效果