ViewPager Details (5) - - Using Fragment to Realize ViewPager Sliding

ViewPager Details (5) - - Using Fragment to Realize ViewPager Sliding

2014-08-18 15:03 61791 people read comment(34) Collection Report
This article has been included in:
Classification:
5. andriod Development (149)

Copyright Statement: This article is the original article of the blogger. It can not be reproduced without the permission of the blogger.

Catalog (?)[+]

  1. A Summary
    1. Class Overview
  2. 2. Realization
    1. Adapter Implementation FragmentPager Adapter
      1. public abstract Fragment getItem int position
    2. Three Fragment s
    3. Main activity implementation
    4. Possible problems

Preface: Previous articles have explained the general implementation of ViewPager, but Android One of the most recommended implementations officially is to use fragments. Now let's use fragments to re-implement the first one. <ViewPager Detailed Explanation (1) - - Basic Introduction The effect achieved.


Series of articles:

1,ViewPager Details (1) - Basic Introduction

2,ViewPager Explanation (2) - Explaining the Four Functions in detail

3,ViewPager Details (3) - - Similarities and Differences between Pager TabStrip and Pager TitleStrip Adding Title Bar

4,<ViewPager Detailed Explanation (4) - - Autonomous Realization of Sliding Indicator

Other related articles:

5,Android Fragment Completely Resolves, Everything You Need to Know About Fragments

6,"Nested viewpager in fragments, multiple fragments in vierpager"


The effect chart of this article:

Add a Btn on the first page. The first page slides to the second page.

  

The second page slides to the third page


I. Overview

From the previous articles, we know that there is an adapter to implement ViewPager. The adapter we used before is Pager Adapter. For fragment, the adapter it uses is Fragment Pager Adapter. Let's first look at the official explanation for this kind of adapter.

Original:

Class Overview

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

When using FragmentPagerAdapter the host ViewPager must have a valid ID set.

Subclasses only need to implement getItem(int) and getCount() to have a working adapter.

Translated: (Poor translation, you can add in the comments)

Fragment Pager Adapter is derived from Pager Adapter. It is used to render fragment pages, which are always stored in fragment manager so that users can access them at any time.

This adapter is best used for managing a limited number of static fragment pages. Although invisible views are sometimes destroyed, all fragments accessed by users are saved in memory. So fragment instances save a lot of states, which causes a lot of memory overhead. So if you want to deal with a lot of page switching, it is recommended to use FragmentState Pager Adapter.

Every ViewPager that uses the FragmentPager Adapter has a valid ID collection, which is the Fragments collection (thank you). Husband and wife Classmate's tips)

For derivative classes of FragmentPagerAdapter, just rewrite getItem(int) and getCount().

II. Specific Realization


1. Adapter Implementation-FragmentPager Adapter

First look at the complete code, then go into detail:

  1. public class FragAdapter extends FragmentPagerAdapter {  
  2.   
  3.     private List<Fragment> mFragments;  
  4.       
  5.     public FragAdapter(FragmentManager fm,List<Fragment> fragments) {  
  6.         super(fm);  
  7.         // TODO Auto-generated constructor stub  
  8.         mFragments=fragments;  
  9.     }  
  10.   
  11.     @Override  
  12.     public Fragment getItem(int arg0) {  
  13.         // TODO Auto-generated method stub  
  14.         return mFragments.get(arg0);  
  15.     }  
  16.   
  17.     @Override  
  18.     public int getCount() {  
  19.         // TODO Auto-generated method stub  
  20.         return mFragments.size();  
  21.     }  
  22.   
  23. }  
public class FragAdapter extends FragmentPagerAdapter {

	private List<Fragment> mFragments;
	
	public FragAdapter(FragmentManager fm,List<Fragment> fragments) {
		super(fm);
		// TODO Auto-generated constructor stub
		mFragments=fragments;
	}

	@Override
	public Fragment getItem(int arg0) {
		// TODO Auto-generated method stub
		return mFragments.get(arg0);
	}

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

}
There are three functions. According to the official documentation in the first part, for derivative classes of FragmentPagerAdapter, just rewrite getItem(int) and getCount().

For the constructor, a List object of Fragment is applied to save the Fragment object for sliding and initialize it in the creation function:

  1. public FragAdapter(FragmentManager fm,List<Fragment> fragments) {  
  2.     super(fm);  
  3.     // TODO Auto-generated constructor stub  
  4.     mFragments=fragments;  
  5. }  
public FragAdapter(FragmentManager fm,List<Fragment> fragments) {
	super(fm);
	// TODO Auto-generated constructor stub
	mFragments=fragments;
}
Then in getItem(int arg0), according to the passed parameter arg0, to return the fragment to be displayed. The following is the official explanation of getItem, which is not very difficult and will not be discussed in detail.

public abstract Fragment getItem (int position)

Return the Fragment associated with a specified position.

Finally, getCount() returns the total number of fragment s used for sliding.

From the constructor, we can see that we need to construct a set of fragments, so we will first generate the fragments class we need.

2. Three Fragment s

The first Fragment class:

XML: (layout1.xml)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#ffffff"  
  6.     android:orientation="vertical" >  
  7.       
  8.     <Button android:id="@+id/fragment1_btn"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="show toast"  
  12.         />  
  13. </LinearLayout>  
<?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:background="#ffffff"
    android:orientation="vertical" >
    
    <Button android:id="@+id/fragment1_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show toast"
        />
</LinearLayout>
A Btn is added to it.

Java Code:

  1. public class Fragment1 extends Fragment {  
  2.       
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  5.             Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         View view= inflater.inflate(R.layout.layout1, container, false);  
  8.           
  9.         //Operating methods for controls in View  
  10.         Button btn = (Button)view.findViewById(R.id.fragment1_btn);  
  11.         btn.setOnClickListener(new View.OnClickListener() {  
  12.               
  13.             @Override  
  14.             public void onClick(View v) {  
  15.                 // TODO Auto-generated method stub  
  16.                 Toast.makeText(getActivity(), "Click on the first fragment Of BTN", Toast.LENGTH_SHORT).show();  
  17.             }  
  18.         });  
  19.         return view;  
  20.     }  
  21. }  
public class Fragment1 extends Fragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view= inflater.inflate(R.layout.layout1, container, false);
		
		//Operating methods for controls in View
		Button btn = (Button)view.findViewById(R.id.fragment1_btn);
		btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "Click on the first fragment Of BTN", Toast.LENGTH_SHORT).show();
			}
		});
		return view;
	}
}
Return to the View to be displayed in onCreateView(). The above code simply demonstrates how to manipulate the controls in the view. It is not very difficult. If you are not familiar with Fragment, please read this article first. <Android Fragment completely parses everything you need to know about debris.

The second Fragment class:

XML code: (layout2.xml) native code, no changes

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#ffff00"  
  6.     android:orientation="vertical" >  
  7.       
  8.   
  9. </LinearLayout>  
<?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:background="#ffff00"
    android:orientation="vertical" >
    

</LinearLayout>
java code:
  1. public class Fragment2 extends Fragment {  
  2.       
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  5.             Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         View view=inflater.inflate(R.layout.layout2, container, false);  
  8.         return view;  
  9.     }  
  10.   
  11. }  
public class Fragment2 extends Fragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.layout2, container, false);
		return view;
	}

}

The third Fragment class:

XML code: (layout3.xml) Similarly, native code, without any changes

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#ff00ff"  
  6.     android:orientation="vertical" >  
  7.       
  8.   
  9. </LinearLayout>  
<?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:background="#ff00ff"
    android:orientation="vertical" >
    

</LinearLayout>
java code:
  1. public class Fragment3 extends Fragment {  
  2.       
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  5.             Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         View view=inflater.inflate(R.layout.layout3, container, false);  
  8.         return view;  
  9.     }  
  10.   
  11. }  
public class Fragment3 extends Fragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.layout3, container, false);
		return view;
	}

}

3. Implementation of main activity

Core code:

  1. public class MainActivity extends FragmentActivity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.   
  8.         //Constructing an adapter  
  9.         List<Fragment> fragments=new ArrayList<Fragment>();  
  10.         fragments.add(new Fragment1());  
  11.         fragments.add(new Fragment2());  
  12.         fragments.add(new Fragment3());   
  13.         FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);  
  14.           
  15.         //Setting the adapter  
  16.         ViewPager vp = (ViewPager)findViewById(R.id.viewpager);  
  17.         vp.setAdapter(adapter);  
  18.     }  
  19.   
  20. }  
public class MainActivity extends FragmentActivity {

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

        //Constructing an adapter
        List<Fragment> fragments=new ArrayList<Fragment>();
        fragments.add(new Fragment1());
        fragments.add(new Fragment2());
        fragments.add(new Fragment3()); 
        FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);
        
        //Setting the adapter
        ViewPager vp = (ViewPager)findViewById(R.id.viewpager);
        vp.setAdapter(adapter);
    }

}

First of all, one of the most noteworthy points is that Activity is derived from Fragment Activity. Actually, this is the basic knowledge of Fragment. Only Fragment Activity can embed fragment pages. Ordinary Activity can't.

This code is divided into two steps: the first step is to construct the adapter; the second step is to set the adapter.

Look first at the process of constructing adapters:

  1. //Constructing an adapter  
  2. List<Fragment> fragments=new ArrayList<Fragment>();  
  3. fragments.add(new Fragment1());  
  4. fragments.add(new Fragment2());  
  5. fragments.add(new Fragment3());   
  6. FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);  
//Constructing an adapter
List<Fragment> fragments=new ArrayList<Fragment>();
fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3()); 
FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);
Construct a fragment list, then add the corresponding instances of the three fragment classes above, and finally generate the FragAdapter instance.
As for the second step, there's nothing to say about setting up an adapter.

4. Possible problems

Question: In MainActivity, when you write this sentence: fragments. add (new Fragment 1 ()); when you add an instance of a Fragment object to the Fragment list, you will be prompted that "Fragment 1 () cannot be converted to fragment"

Solution: This is due to inconsistent import packages. The general problem is that in Fragment1, android.app.Fragment is imported, and here the import class is: android.support.v4.app.Fragment. Of course, different packages can not be converted. Unified import into android.support.v4.app.Fragment is normal. Reference article android cannot convert from Fragment1 to Fragment>



Source download address: http://download.csdn.net/detail/harvic880925/7777849

Please respect the copyright of the originator. Please indicate the origin when reproducing: http://blog.csdn.net/harvic880925/article/details/38660861 Thank you very much!


top 40 step on 3
 
 

My Similar Articles

5. andriod Development (149)
http://blog.csdn.net More articles

Tags: Fragment Android xml encoding

Posted on Mon, 08 Jul 2019 15:28:22 -0400 by new@php