Viewpager (v)-----Using fragment to achieve Viewpager sliding

Source: Internet
Author: User
Tags constructor stub xmlns

Preface: The previous article explained Viewpager's common realization method, but the Android official most recommended one kind of realization method is uses the fragment, below we use fragment to re-realize the first "Viewpager detailed (a)---basic introduction" The effect that is achieved.


Series Articles:

1, "Viewpager detailed (a)---basic introduction"

2, "Viewpager detailed (ii)---four functions"

3, "Viewpager detailed (three)---pagertabstrip and pagertitlestrip add the title bar similarities and differences"

4, "Viewpager detailed (four)----autonomous realization of sliding indicator bar"

Other related articles:

5, "Android fragment full resolution, about the debris you need to know everything"

6, "Fragment nested Viewpager,vierpager in a number of fragment"


This effect diagram:

On the first page plus a BTN first page slide for the second page


Second page slide for third page


I. Overview

From the previous articles, we know that the implementation of Viewpager is to have adapters, the adapter we used before is pageradapter, and for fragment, The adapter that it uses is: Fragmentpageradapter. Take a look at the official explanation for this class: (Chinese explanation in English)

Original:

Class Overview

Implementation of Pageradapter that represents each page as a Fragment that's persistently kept in the Fragment manager a s long as the user can return to the page.

This version of the pager was best for use when there was 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 would be is kept in memory, and though its view hierarchy could be destroyed if not Visi ble. This can result with using a significant amount of memory since fragment instances can hold on to an arbitrary amount of STA Te. For larger sets of pages, consider Fragmentstatepageradapter.

When using Fragmentpageradapter the host Viewpager must has a valid ID set.

Subclasses only need to implement GetItem (int.) and GetCount () to has a working adapter. Translation : (not good, you can add in the comments)

Fragmentpageradapter is derived from Pageradapter, which is used to render fragment pages, and these fragment pages are kept in Fragment manager so that users can access them at any time.

This adapter is best used for the management of a limited static fragment page. Although invisible views are sometimes destroyed, all fragment accessed by the user are saved in memory. Therefore, fragment instances save a large number of States, which results in significant memory overhead. So if you're dealing with a lot of page transitions, we recommend using Fragmentstatepageradapter.

Every viewpager that uses Fragmentpageradapter has a valid collection of IDs, and a collection of valid IDs is a collection of fragment (thanks to the tips of the students)

For Fragmentpageradapter derived classes, you only need to rewrite getitem (int) and GetCount (). Second, the concrete realization


1, adapter implementation--fragmentpageradapter

First look at the complete code, and then say:

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 ();
	}

}
Here are three functions, according to the official document of the first part, it is known that for fragmentpageradapter derived classes, only getitem (int) and GetCount () can be overridden.

For constructors, a fragment list object is applied here to hold the fragment object for sliding and initialize it in the creation function:

Public Fragadapter (Fragmentmanager fm,list<fragment> fragments) {
	super (FM);
	TODO auto-generated constructor stub
	mfragments=fragments;
}
Then in GetItem (int arg0), according to the parameters of the arg0, to return the current to show the fragment, the following is the official explanation of GetItem, not very difficult, not detailed.

Public abstract Fragment getItem (int position)

Return the Fragment associated with a specified position. Finally, GetCount () returns the total number of fragment used for sliding;

From the constructor, we can see that we are going to construct a collection of fragment, so we will first produce the fragment class we need;

2, three fragment class

First Class of fragment:

XML: (layout1.xml)

<?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>
In which a BTN was added

Java code:

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);
		
		How to manipulate a control in a 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 (), "clicked on the first fragment btn", Toast.length_short). Show ();
		});
		return view;
	}
}
In Oncreateview () return to display the view, the above code is a simple demonstration of how to manipulate the control on the view, it is not very difficult, no longer detailed, if the fragment is not familiar with the classmate, first look at this article: "Android fragment fully Parse, Everything you need to know about fragmentation

The second class of fragment:

XML code: (layout2.xml) native code, without making any changes

<?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:
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 class of fragment:

XML code: (Layout3.xml) Same, native code, no changes made

<?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:
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. Main activity Implementation

Core code:

public class Mainactivity extends Fragmentactivity {

    @Override
    protected void OnCreate (Bundle Savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);

        Construction 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);
        
        Set adapter
        Viewpager VP = (viewpager) Findviewbyid (R.id.viewpager);
        Vp.setadapter (adapter);
    }

}

First of all, there is a most noteworthy place: activity derived from fragmentactivity, in fact, this is the basic knowledge about fragment, only fragmentactivity to embed fragment page, normal activity is not. This code is divided into two main steps, the first step: construct the adapter, and the second step: set the adapter.

First look at the process of constructing the adapter:

Construction 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 list of fragment, then add the corresponding instances of the three fragment classes above, and finally generate the Fragadapter instance.
As for the second step, set the adapter, there is nothing to say.

4. Problems that may arise

Question: In Mainactivity, when writing this sentence: Fragments.add (new Fragment1 ()); When you add an Fragement object instance to the fragment list, you are prompted to "cannot convert Fragment1 () to Fragment"

Workaround: This is because the import package is inconsistent, the general problem is that: import in Fragment1 is Android.app.Fragment, and here the Import class is: Android.support.v4.app.Fragment, Package is different, of course, can not be converted, unified import as android.support.v4.app.Fragment after normal. Reference article "Android cannot convert from Fragment1 to Fragment"



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

Please respect the original copyright, reproduced please indicate the source: http://blog.csdn.net/harvic880925/article/details/38660861 greatly appreciated.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.