Android使用ActionBar和ViewPager切换页面

演示效果如下:
技术分享

项目布局如下:
技术分享
技术分享

MainActivity.java代码

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;

import com.xuliugen.fragment.ChatFragment;
import com.xuliugen.fragment.FriendFragment;
import com.xuliugen.fragment.MomentFragment;
import com.xuliugen.fragment.MoreFragment;

public class MainActivity extends ActionBarActivity implements TabListener,OnPageChangeListener {

    private List<MyTab> tabsList = new ArrayList<MainActivity.MyTab>(4);
    private ViewPager viewPager;// ViewPager用于存放fragment
    private ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 添加4个fragment到自定义的Tab中去
        tabsList.add(new MyTab("聊天", ChatFragment.class));
        tabsList.add(new MyTab("朋友", FriendFragment.class));
        tabsList.add(new MyTab("时刻", MomentFragment.class));
        tabsList.add(new MyTab("更多", MoreFragment.class));

        initActionBar();

    }

    private void initActionBar() {

        // 找到viewpager
        viewPager = (ViewPager) this.findViewById(R.id.viewpager);
        actionBar = getSupportActionBar(); // 获得v7中的ActionBar
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// 设置为导航模式

        // 通过循环遍历将创建的四个Tab加入到actionBar中
        for (MyTab tab : tabsList) {
            Tab t = actionBar.newTab(); // 使用v7下边的Tab
            t.setText(tab.getText());
            t.setTabListener(this);// 设置TabListener监听器
            actionBar.addTab(t);
        }
        viewPager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
        viewPager.setOnPageChangeListener(this);
    }

    /**
     * 封装一个Tab的类
     * 
     * tab的文字
     * 
     * tab所包含的Class
     */
    class MyTab {

        private String text; // 标题的文字
        private Class fragment;// 每一个tab所对应的页面fragment

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public Class getFragment() {
            return fragment;
        }

        public void setFragment(Class fragment) {
            this.fragment = fragment;
        }

        /**
         * 两个参数的构造方法,便于创建一个对象
         * 
         * @param string
         * @param fragment
         */
        public MyTab(String string, Class fragment) {
            this.text = string;
            this.fragment = fragment;
        }

    }

    /**
     * 为viewpager设置的适配器
     */
    class TabFragmentPagerAdapter extends FragmentPagerAdapter {

        public TabFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {

            try {
                return (Fragment) tabsList.get(i).getFragment().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public int getCount() {
            return tabsList.size();
        }

    }

    /************* 下边是TabListener所实现的方法 ***********************/

    /**
     * 当Tab被双次选中
     */
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {

    }

    /**
     * 当Tab被单次选中
     */
    @Override
    public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {

    }

    /**************** 下边是OnPageChangeListener实现的方法 ****************/
    @Override
    public void onPageScrollStateChanged(int i) {
    }

    @Override
    public void onPageScrolled(int i, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int i) {
        actionBar.selectTab(actionBar.getTabAt(i));
    }

}

下边是四个fragment

public class ChatFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_friends, container, false);
    }
}
public class FriendFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }
}
public class MomentFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_moment, container, false);
    }
}
public class MoreFragment extends Fragment {

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

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="fill_parent"
        android:layout_height="fill_parent" >
    </android.support.v4.view.ViewPager>

</RelativeLayout>

下边是四个fragment的布局文件

<?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="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="聊天" >
    </TextView>

</LinearLayout>

其他三个都一样只是文件名和里边的内容改变了一下。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。