Android ViewPager nested Fragment to achieve page sliding

ViewPager nested Fragment to realize page sliding

PagerAdapter has two subclasses: FragmentPagerAdapter and FragmentStatePagerAdapter, they are all used to adapt the data to the ViewPager appearing in the support package. FragmentPagerAdapter has its own caching strategy. When used in conjunction with ViewPager, it will cache the current Fragment and one on the left and one on the right, a total of three Fragment objects. FragmentStatePagerAdapter is a subclass of PagerAdapter. This adapter is very useful for sliding multiple Fragment interfaces. It works very similarly to listview. When the Fragment is not visible to the user, the entire Fragment will be destroyed, and only the Fragment's save state will be saved. Based on such characteristics, FragmentStatePagerAdapter is more suitable for conversion between many interfaces than FragmentPagerAdapter, and consumes less memory resources. FragmentStatePagerAdapter is used here to realize the sliding switch between 10 pages. Buy a page and load a ListFragment. And two buttons are provided at the bottom of the view, one to jump to the first page and one to jump to the last page.

  效果图:

Write a picture description here

  为了贴代码简单,我把所有的类,包括:一个FragmentActivity的子类,一个ListFragment的子类,以及一个FragmentStatePagerAdapter的子类都写在同一个class文件中,源码如下:
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
    private ViewPager viewPager;
    private static final int NUMBER = 10; // 定义页数
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        // 添加按键监听事件
        this.findViewById(R.id.first).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                viewPager.setCurrentItem(0);// 点击按钮,跳到第一页
            }
        });
        // 添加按键监听事件
        findViewById(R.id.last).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                viewPager.setCurrentItem(NUMBER - 1); // 点击按钮, 跳到最后一页
            }
        });
        viewPager.setAdapter(new myAdapter(getSupportFragmentManager()));
    }

    // 给ViewPager自定义一个适配器
    public static class myAdapter extends FragmentStatePagerAdapter {

        public myAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
        }

        @Override
        public Fragment getItem(int arg0) {
            // TODO Auto-generated method stub
            return ArrayListFragment.getFragment(arg0);// 获取一个Fragment并且返回
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return NUMBER;// 返回长度、个数
        }

    }

    // 定义一个Fragment
    public static class ArrayListFragment extends ListFragment {
        private TextView textView;
        int num;

        public static ArrayListFragment getFragment(int num) {// 定义一个方法,返回一个Fragment并且传递一个参数
            ArrayListFragment arrayListFragment = new ArrayListFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("num", num);
            arrayListFragment.setArguments(bundle);// 传递参数
            return arrayListFragment;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {// 启动时在调用onCreate后调用
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_expandable_list_item_1, getData()));// 给ListFragment创建一个适配器
        }

        public List<String> getData() {// 给ListFragment提供一组数据
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < 20; i++) {
                list.add("第 -" + i + "- 行");
            }
            return list;
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
            // ListFragment点击监听事件
            Toast.makeText(getActivity(), "正在点击第" + num + "页,第" + id + "行", 1)
                    .show();
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            // 获取Fragment传递过来的值,如果为空则赋值1;
            num = (getArguments() != null ? getArguments().getInt("num") : 1);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            // 给Fragment加载视图
            View view = inflater.inflate(R.layout.fragment_layout, null);
            textView = (TextView) view.findViewById(R.id.fragment_textView1);
            textView.setText("第 -" + num + "- 页");
            return view;
        }

        @Override
        public void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
        }
    }
}

Two layout files, one for Activity and one for ListFragment.

Activity layout file:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="9"
        android:orientation="vertical" >

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </android.support.v4.view.ViewPager>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/first"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="跳到第一页" />

        <Button
            android:id="@+id/last"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="跳到最后一页" />
    </LinearLayout>

</LinearLayout>

List 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="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/fragment_textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="7"
        android:orientation="vertical" >

        <ListView
            android:id="@id/android:list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

Note: The ListView ID in ListFragment must be defined as android: id = ”@ id / android: list”, which is loaded in the program using setlistAdapter.

Published 34 original articles · Like 10 · Visits 30,000+

Guess you like

Origin blog.csdn.net/q296264785/article/details/53316772