Android FragmentStatePageAdapter的使用Demo

上一篇寫過FragmentPagerAdapter,這篇來介紹FragmentStatePagerAdapter,那麼二者之間有何差異呢:html

FragmentPagerAdapter不少其它的用於少許界面的ViewPager,比方Tab。劃過的fragment會保存在內存中,雖然已經劃過。而FragmentStatePagerAdapter和ListView有點相似,會保存當前界面,以及下一個界面和上一個界面(假設有),最多保存3個,其它會被銷燬掉。
java

假設想要更具體的瞭解,可以查看官網API,如下給出依照官網上寫出的Demo:android

實現效果圖:app

源碼:ide


佈局文件:佈局

fragment_pager.xml(佈局了ViewPager和兩個button):
this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="4dip" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:gravity="center"
        android:measureWithLargestChild="true"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/goto_first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="調到首頁" >
        </Button>

        <Button
            android:id="@+id/goto_last"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="調到尾頁" >
        </Button>
    </LinearLayout>

</LinearLayout>

fragment_pager_list.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:drawable/gallery_thumb"
    android:orientation="vertical" >

    <!-- 該Textview用來顯示Fragment的頁數 -->

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:text="@string/hello_world"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <!-- 不爲空用來顯示ListView,假設爲空,則顯示TextView(數據爲空) -->

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawSelectorOnTop="false" />

        <TextView
            android:id="@android:id/empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="數據爲空"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </FrameLayout>

</LinearLayout>

代碼文件:

MainActivity:spa

package com.fragmentdemo13_fragmentstatepageradapter;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
 * 這裏咱們調用的是support.v4的包,因此MainActivity繼承的是FragmentActivity,而不是Activity。
 */
public class MainActivity extends FragmentActivity {
	public static final int NUM_ITEMS = 10;
	private MyAdapter mAdapter;
	private ViewPager mPager;
	private Button button_first, button_last;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_pager);
		/**
		 * 相同,由於調用的是support.v4的包,這裏是getSupportFragmentManager(),而不是getFragmentManager();
		 */
		mAdapter = new MyAdapter(getSupportFragmentManager());

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);
		/**
		 * 點擊返回首頁
		 */
		button_first = (Button) findViewById(R.id.goto_first);
		button_first.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mPager.setCurrentItem(0);
			}
		});
		/**
		 * 點擊返回尾頁
		 */
		button_last = (Button) findViewById(R.id.goto_last);
		button_last.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mPager.setCurrentItem(NUM_ITEMS - 1);
			}
		});

	}

}

MyAdapter.java:

package com.fragmentdemo13_fragmentstatepageradapter;

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

/**
 * 這裏繼承的是FragmentStatePagerAdapter, 依據官方API的介紹,當項目中遇到使用大量的列表頁面時,使用該適配器是個更好的選擇。
 * (This version of the pager is more useful when there are a large number of
 * pages, working more like a list view.)
 */
public class MyAdapter extends FragmentStatePagerAdapter {

	public MyAdapter(FragmentManager fm) {
		super(fm);
	}
	/**
	 * 僅僅需要實現如下兩個方法就能夠。
	 */
	@Override
	public Fragment getItem(int position) {
		return ArrayListFragment.newInstance(position);
	}

	@Override
	public int getCount() {
		return MainActivity.NUM_ITEMS;
	}

}

ArrayListFragment.java:

package com.fragmentdemo13_fragmentstatepageradapter;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ArrayListFragment extends ListFragment {
	private int mNum;
	public ArrayList<String> list = new ArrayList<String>();

	/**
	 * 建立一個計算Fragment頁面的實例,將怒num做爲一個參數。
	 * (Create a new instance of
	 * CountingFragment, providing "num" as an argument.)
	 */
	public static ArrayListFragment newInstance(int num) {

		ArrayListFragment f = new ArrayListFragment();
		Bundle args = new Bundle();
		args.putInt("num", num);
		f.setArguments(args);

		return f;
	}

	/**
	 * 當調用該方法時,檢索此實例的數量的參數。
	 * (When creating, retrieve this instance's number from
	 * its arguments.)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mNum = getArguments() != null ? getArguments().getInt("num") : 1;
	}

	/**
	 * Fragment的UI僅僅顯示它所在的頁碼。
	 * (The Fragment's UI is just a simple text view
	 * showing its instance number.)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_pager_list, container,
				false);
		TextView tv = (TextView) view.findViewById(R.id.text);
		tv.setText("Fragment #" + mNum);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListAdapter(new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, getData()));
	}

	/**
	 * 在每一個Fragment列表中展現的數據。
	 */
	private ArrayList<String> getData() {
		for (int i = 0; i < 20; i++) {
			list.add("nihao" + i);
		}
		return list;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		Toast.makeText(getActivity(), "您點擊了"+position, 0).show();
	}

}

源碼下載:

點擊下載源代碼
.net

相關文章
相關標籤/搜索