ViewPager+fragment的使用

如图我在一个继承FragmentActivity的类中嵌套了3个fragment分别能实现3个不同的界面,默认展现第一个,在第一个的fragment中有个ViewPager在ViewPager中嵌套了3个不同的fragment来实现页面的跳转

主界面的代码

package org.xml.demo.fragment;

import ogg.huanxin.huadong.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MyFragmentDemo extends FragmentActivity {

    private int index;
    // 当前fragment的index
    private int currentTabIndex;
    private Fragment[] fragments;
    private Button[] buttons;

    private HomeFeagment homeFeagment;
    private FengqiangFragment fengqiangFragment;
    private PinPaiFragment pinPaiFragment;

    @Override
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method stub
        super.onCreate(arg0);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.setContentView(R.layout.myviewpagerdemo);
        setFindViewById();
        setListener();
        setControll();

    }

    private void setFindViewById() {
        // TODO Auto-generated method stub
        buttons = new Button[3];
        buttons[0] = (Button) findViewById(R.id.bb_viewdemo_shou);
        buttons[1] = (Button) findViewById(R.id.bb_viewdemo_qiang);
        buttons[2] = (Button) findViewById(R.id.bb_viewdemo_pinpai);
        // 把第一个设置成默认选中状态
        buttons[0].setSelected(true);

    }

    private void setListener() {
        // TODO Auto-generated method stub

    }

    private void setControll() {
        // TODO Auto-generated method stub
        homeFeagment = new HomeFeagment();
        fengqiangFragment = new FengqiangFragment();
        pinPaiFragment = new PinPaiFragment();

        fragments = new Fragment[] { homeFeagment, fengqiangFragment,
                pinPaiFragment };
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.rl_viewdemo_fragment, homeFeagment)
                .add(R.id.rl_viewdemo_fragment, fengqiangFragment)
                .add(R.id.rl_viewdemo_fragment, pinPaiFragment)
                .hide(fengqiangFragment).hide(pinPaiFragment)
                .show(homeFeagment).commit();
    }

    public void OnSeclet(View view) {
        switch (view.getId()) {
        case R.id.bb_viewdemo_shou:
            index = 0;
            System.out.println("ProducteTimeLimit-----" + index);
            break;
        case R.id.bb_viewdemo_qiang:
            index = 1;
            System.out.println("MyFragent" + index);
            break;
        case R.id.bb_viewdemo_pinpai:
            index = 2;
            break;

        }
        if (currentTabIndex != 0) {
            buttons[0].setSelected(false);
        }
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager()
                    .beginTransaction();
            trx.hide(fragments[currentTabIndex]);

            if (!fragments[index].isAdded()) {
                trx.add(R.id.rl_viewdemo_fragment, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        buttons[currentTabIndex].setSelected(false);
        // 把当前tab设为选中状态
        buttons[index].setSelected(true);
        currentTabIndex = index;
    }

}

主界面xml的代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff" >

    <LinearLayout
        android:id="@+id/ll_viewedemo_top"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#999999" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:baselineAligned="false"
            android:gravity="center"
            android:orientation="horizontal" >

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >

                <Button
                    android:id="@+id/bb_viewdemo_shou"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@android:color/white"
                    android:onClick="OnSeclet"
                    android:drawableTop="@drawable/main_topcolor"
                    android:gravity="center_vertical|center"
                    android:text="首页"
                    android:textColor="@color/main_bottoncolor"
                    android:textSize="15sp" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >

                <Button
                    android:id="@+id/bb_viewdemo_qiang"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:onClick="OnSeclet"
                    android:background="@android:color/white"
                    android:drawableTop="@drawable/main_topcolor"
                    android:gravity="center_vertical|center"
                    android:text="最后疯抢"
                    android:textColor="@color/main_bottoncolor"
                    android:textSize="15sp" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" >

                <Button
                    android:id="@+id/bb_viewdemo_pinpai"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:onClick="OnSeclet"
                    android:background="@android:color/white"
                    android:drawableTop="@drawable/main_topcolor"
                    android:gravity="center_vertical|center"
                    android:text="品牌抢购"
                    android:textColor="@color/main_bottoncolor"
                    android:textSize="15sp" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_viewdemo_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/ll_viewedemo_top" >
    </RelativeLayout>

</RelativeLayout>
View Code

其中默认显示主界面的代码为

package org.xml.demo.fragment;

import java.util.ArrayList;

import ogg.huanxin.huadong.R;
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.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class HomeFeagment extends Fragment {
    private ViewPager mPager;
    private TextView barText;
    private TextView view1, view2, view3;
    private ArrayList<Fragment> fragmentlist;
    private int currIndex;// 当前的叶卡标号

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        InitTextView();
        InitTextBar();
        InitViewPager();
    }

    /*
     * 初始化标签名字
     */
    private void InitTextView() {
        view1 = (TextView) getActivity().findViewById(R.id.hometext1);
        view2 = (TextView) getActivity().findViewById(R.id.hometext2);
        view3 = (TextView) getActivity().findViewById(R.id.hometext3);

        view1.setOnClickListener(new txListener(0));
        view2.setOnClickListener(new txListener(1));
        view3.setOnClickListener(new txListener(2));
    }

    private class txListener implements View.OnClickListener {
        private int index = 0;

        public txListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mPager.setCurrentItem(index);
        }
    }

    /*
     * 初始化图片的位移像素
     */
    private void InitTextBar() {
        // TODO Auto-generated method stub
        // barText = (TextView) super.findViewById(R.id.cursor);
        barText = (TextView) getActivity().findViewById(R.id.homecursor);
        Display display = getActivity().getWindow().getWindowManager()
                .getDefaultDisplay();
        // 得到显示的屏宽度
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        int tabLimeLength = metrics.widthPixels / 3;
        LayoutParams lp = (LayoutParams) barText.getLayoutParams();
        lp.width = tabLimeLength;
        barText.setLayoutParams(lp);
    }

    /*
     * 初始化ViewPager
     */
    private void InitViewPager() {
        // TODO Auto-generated method stub
        mPager = (ViewPager) getActivity().findViewById(R.id.vhomePager);
        fragmentlist = new ArrayList<Fragment>();
        Fragment fragment = new Fragment1();
        Fragment fragment2 = new Fragmentview2();
        Fragment fragment3 = new Fragmentview3();
        fragmentlist.add(fragment);
        fragmentlist.add(fragment2);
        fragmentlist.add(fragment3);
        // 给ViewPager添加适配器

        // 给ViewPager设置适配器
        mPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(),
                fragmentlist));
        // 设置当前显示标签页为第一页
        mPager.setCurrentItem(0);
        // mPager.setOnPageChangeListener(new MyPn);
        // 页面变化时的监听器
        mPager.setOnPageChangeListener(new MyOnpageChangeListener());
    }

    

    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> list;

        public MyFragmentPagerAdapter(FragmentManager fm,
                ArrayList<Fragment> list) {
            super(fm);
            this.list = list;
            // TODO Auto-generated constructor stub
        }

        // 得到每个item
        @Override
        public Fragment getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.get(arg0);
        }

        // 初始化每个页面选项
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            return super.instantiateItem(container, position);
        }

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

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return super.getItemPosition(object);
        }

    }

    private class MyOnpageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            /*
             * 此方法是在状态改变的时候调用,其中arg0这个参数 有三种状态(0,1,2)。arg0
             * ==1的时辰默示正在滑动,arg0==2的时辰默示滑动完毕了,arg0==0的时辰默示什么都没做。
             */
            if (arg0 == 0) {
                Log.e("-----------", ">>>>>>>>>>onpageselected==0");
            } else if (arg0 == 1) {
                Log.e("-----------", ">>>>>>>>>>onpageselected==1");
            } else if (arg0 == 2) {
                Log.e("-----------", ">>>>>>>>>>onpageselected==2");
            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            /*
             * onPageScrolled(int arg0,float arg1,int arg2)
             * ,当页面在滑动的时候会调用此方法,在滑动被停止之前,此方法回一直得到 调用。 其中三个参数的含义分别为: arg0:当前页面,
             * 及你点击滑动的页面 arg1:当前页面偏移的百分比 arg2:当前页面偏移的像素位置
             */
            Log.e("-----------", "------------>>>>onpagescrolled>>>arg0=="
                    + arg0 + ">>>arg1==" + arg1 + ">>>arg2==" + arg2);

            LinearLayout.LayoutParams ll = (LayoutParams) barText
                    .getLayoutParams();
            if (currIndex == arg0) {
                ll.leftMargin = (int) (currIndex * barText.getWidth() + arg1
                        * barText.getWidth());
            } else if (currIndex > arg0) {
                ll.leftMargin = (int) (currIndex * barText.getWidth() - (1 - arg1)
                        * barText.getWidth());
            }
            barText.setLayoutParams(ll);
        }

        @Override
        public void onPageSelected(int arg0) {
            /*
             * onPageSelected(int arg0) : 此方法是页面跳转完后得到调用,
             * arg0是你当前选中的页面的Position(位置编号)。
             */
            currIndex = arg0;

        }

    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eee" >

    <LinearLayout
        android:id="@+id/ll_main_text"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#FF7200"
        android:gravity="center_vertical" >

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:gravity="center" >

            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:contentDescription="@null"
                android:scaleType="fitCenter"
                android:src="@drawable/arrow_left" />
        </LinearLayout>

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#FE8B40" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.8"
            android:gravity="center"
            android:text="限时购"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#FE8B40" />

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:gravity="center" >

            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:contentDescription="@null"
                android:scaleType="fitCenter"
                android:src="@drawable/dropdown" />
        </LinearLayout>
    </LinearLayout>

    <!--  -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/ll_main_text"
        android:background="@android:color/white"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearlayout1"
            android:layout_width="match_parent"
            android:layout_height="50.0dip"
            android:layout_gravity="center"
            android:background="#FFFFFF" >

            <TextView
                android:id="@+id/hometext1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:gravity="center"
                android:text="页卡1"
                android:textColor="#000000"
                android:textSize="22.0dip" />

            <TextView
                android:id="@+id/hometext2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:gravity="center"
                android:text="页卡2"
                android:textColor="#000000"
                android:textSize="22.0dip" />

            <TextView
                android:id="@+id/hometext3"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:gravity="center"
                android:text="页卡3"
                android:textColor="#000000"
                android:textSize="22.0dip" />
        </LinearLayout>

        <TextView
            android:id="@+id/homecursor"
            android:layout_width="250dp"
            android:layout_height="5dp"
            android:background="#990033" />

        <android.support.v4.view.ViewPager
            android:id="@+id/vhomePager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="#eee"
            android:flipInterval="30"
            android:persistentDrawingCache="animation" />
    </LinearLayout>

</RelativeLayout>
View Code

第二个fragment代码和xml

package org.xml.demo.fragment;

import ogg.huanxin.huadong.R;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FengqiangFragment extends Fragment implements OnClickListener {
    private Button dialogButton;
    private ProgressDialog progressDialog;

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setFindViewById();
        setListener();
        setControll();
    }

    private void setFindViewById() {
        // TODO Auto-generated method stub
        dialogButton = (Button) getActivity().findViewById(
                R.id.bb_fengqiang_dialog);
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在跳转");
        // 设置返回键不能将其取消
        progressDialog.setCancelable(false);
    }

    private void setListener() {
        // TODO Auto-generated method stub
        dialogButton.setOnClickListener(this);
    }

    private void setControll() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
        case R.id.bb_fengqiang_dialog:
            dialogSet();
            break;

        default:
            break;
        }
    }

    /*
     * 设置一个警告框
     */
    private void dialogSet() {
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new Builder(getActivity());
        builder.setTitle("是否跳转");
        builder.setMessage("当点击    确定    时 会出现个圆形的进度条  在5秒后 自动消失 ...");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                progressDialog.show();
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        progressDialog.dismiss();
                    }
                }, 5000);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        builder.create().show();
    }
}
View Code
<?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:orientation="vertical" >

    <LinearLayout
        android:id="@+id/ll_main_text"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#FF7200"
        android:gravity="center_vertical" >

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:gravity="center" >

            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:contentDescription="@null"
                android:scaleType="fitCenter"
                android:src="@drawable/arrow_left" />
        </LinearLayout>

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#FE8B40" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.8"
            android:gravity="center"
            android:text="限时购"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#FE8B40" />

        <LinearLayout
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:gravity="center" >

            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:contentDescription="@null"
                android:scaleType="fitCenter"
                android:src="@drawable/dropdown" />
        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/bb_fengqiang_dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="hello word" />

</LinearLayout>
View Code

第三个fragment

package org.xml.demo.fragment;

import ogg.huanxin.huadong.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PinPaiFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.pinpaifragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);        
    }
}
原文地址:https://www.cnblogs.com/wangfengdange/p/4978432.html