Fragment imbriqué de ViewPager pour réaliser le glissement de page
PagerAdapter a deux sous-classes: FragmentPagerAdapter et FragmentStatePagerAdapter, elles sont toutes utilisées pour adapter les données au ViewPager apparaissant dans le package de support. FragmentPagerAdapter a sa propre stratégie de mise en cache. Lorsqu'il est utilisé avec ViewPager, il mettra en cache le fragment actuel et un à gauche et un à droite, soit un total de trois objets Fragment. FragmentStatePagerAdapter est une sous-classe de PagerAdapter. Cet adaptateur est très utile pour faire glisser plusieurs interfaces Fragment. Il fonctionne de manière très similaire à listview. Lorsque le fragment n'est pas visible pour l'utilisateur, le fragment entier sera détruit et seul l'état de sauvegarde du fragment sera sauvegardé. Sur la base de ces caractéristiques, FragmentStatePagerAdapter est plus adapté à la conversion entre de nombreuses interfaces que FragmentPagerAdapter et consomme moins de ressources mémoire. FragmentStatePagerAdapter est utilisé ici pour réaliser l'interrupteur coulissant entre 10 pages. Achetez une page et chargez un ListFragment. Et deux boutons sont fournis en bas de la vue, un pour passer à la première page et un pour passer à la dernière page.
效果图:
为了贴代码简单,我把所有的类,包括:一个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();
}
}
}
Deux fichiers de mise en page, un pour Activity et un pour ListFragment.
Fichier de mise en page d'activité:
<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>
Liste 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>
Remarque: L'ID ListView dans ListFragment doit être défini comme android: id = ”@ id / android: list”, qui est chargé dans le programme à l'aide de setlistAdapter.