Copyright Statement: This article is the original article of the blogger. It can not be reproduced without the permission of the blogger.
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
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
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 Realization1. Adapter Implementation-FragmentPager Adapter
First look at the complete code, then go into detail:
- 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();
- }
- }
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:
- public FragAdapter(FragmentManager fm,List<Fragment> fragments) {
- super(fm);
- // TODO Auto-generated constructor stub
- mFragments=fragments;
- }
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)
- <?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>
<?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:
- 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;
- }
- }
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
- <?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>
<?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;
- }
- }
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
- <?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>
<?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;
- }
- }
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:
- 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);
- }
- }
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:
- //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);
//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!
- Last article Menu Details (1): Code Implementation System Menu and Submenu
- Next article Declare, use and customize permissions
- •Custom Control Trilogy (3) - WaterFall Layout Implementation of WaterFall Container 2017-04-08 Reading 9393
- •Drawing Chapter of Custom Control Trilogy (19) - Linear Gradient and Flash Text Effect 2016-08-29 Reading 4734
- •Drawing Chapter of Custom Control Trilogy (XVII) - Adding Shadows to Bitmap and Encapsulating Controls 2016-07-12 Reading 5349
- •Drawing Chapter of Custom Control Trilogy (XV) - Implementing Removal Effect of QQ Red Spot Drag (Basic Principle Chapter) 2016-06-08 Reading 10296
- •WebView Using Explanation (2) - WebViewClient and Common Event Listening 2016-05-28 Reading 11427
- •Drawing Chapter of Custom Control Trilogy (14) - Canvas and Layers (2) 2016-05-06 Reading 6576
- •Drawing Chapter of Custom Control Trilogy (20) - Radial Gradient and Water Wave Button Effect 2016-09-24 Reading 6321
- •Drawing Chapter of Custom Control Trilogy (XVIII) - BitmapShader and Telescope Effect 2016-07-26 Reading 4509
- •Drawing Chapter of Custom Control Trilogy (XVI) - Adding Shadow and Luminous Effects to Controls 2016-07-04 Reading 8796
- •WebView Using Explanation (3) - WebChrome Client and LoadData Supplement 2016-06-04 Reading 6295
- •WebView uses Explanation (1) - Native and JS call each other (with JadX decompilation) 2016-05-20 Reading 13525