Home Java javaTutorial Using ViewPager+Fragment in Android App to achieve sliding switching effect

Using ViewPager+Fragment in Android App to achieve sliding switching effect

Jan 13, 2017 am 11:44 AM

In android applications, multi-screen sliding is a very common style. The code implementation without viewpager will be very long. If ViewPager is used, the code will be much shorter. However, using ViewPager also has disadvantages: it needs to import android-support -v4.jar, details cannot be controlled. But now the situation is different. android-support-v4 provides many practical functions, so that now a new android project will import this jar package by default. Then we will also use viewpager to do sliding. Another concept is Fragment and FragmentActivity. Fragment is a special class with a life cycle consistent with activity and an interface consistent with view. That is, Fragment is equal to a View with a life cycle. However, it should be noted that Fragment is not a View. , it has no inheritance relationship with View. The advantage of using Fragment is that Fragment can be reused, and each Fragment can handle its own business internally just like an activity. In this way, the coupling between modules is lower and the internal logic is much clearer than writing all business in an activity. Also, since the business of each module is implemented inside Fragment, the activity only needs to manage several Fragments and does not need to do business-related things. Finally, Fragment can be used to adapt to different resolution models. match. Fragments are available in sdk (android 3.0 and higher) and android-support-v4, but due to compatibility issues, we can only use the fragments in android-support-v4, unless you want your apk to only run on 3.0 On future Android phones, the situation of FragmentActivity will be similar to Fragment. Regarding Fragment and FragmentActivity, there are actually some basic usages that need to be understood. However, considering that Fragment is not the focus of this article, we will not introduce it here. In addition, this article only uses Fragment to make a simple interface, which everyone should understand at a glance. ,well, let's get back to business.

ViewPager + Fragment is often used. The code is extracted from actionbarsherlock. This effect is known to be switched by sliding. Let’s go directly to the code.
Here is a brief explanation of FragmentStatePagerAdapter and FragmentPagerAdapter
2 adapters:
The first fragment state adapter - only the first fragment, the current fragment and the next fragment will exist at present, and the others will be destroyed , suitable for loading multiple data;
The second FragmentPagerAdapter - all exist, so it is not suitable for loading a large amount of data such as pictures, and it is easy to overflow memory.

Project structure:

Android App中使用ViewPager+Fragment实现滑动切换效果

1. activity adapter together (static type Fragment)

public class ViewPageFragment extends FragmentActivity { 
    
  //这个是有多少个 fragment页面 
  static final int NUM_ITEMS = 5; 
  private MyAdapter  mAdapter; 
  private ViewPager  mPager;   
  private int nowPage; 
     
  @Override
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.pagers_fragment_main); 
    mAdapter = new MyAdapter(getSupportFragmentManager() ); 
    mPager = (ViewPager)findViewById(R.id.mypagers_pager); 
    mPager.setAdapter(mAdapter); 
  } 
  
  
  /** 
   * 有状态的 ,只会有前3个存在 其他销毁, 前1个, 中间, 下一个 
   */
  public static class MyAdapter extends  FragmentStatePagerAdapter { 
    public MyAdapter(FragmentManager fm) { 
      super(fm); 
    } 
  
    @Override
    public int getCount() { 
      return NUM_ITEMS; 
    } 
  
    //得到每个item 
    @Override
    public Fragment getItem(int position) { 
      return ArrayFragment.newInstance(position); 
    } 
  
      
    // 初始化每个页卡选项 
    @Override
    public Object instantiateItem(ViewGroup arg0, int arg1) { 
      // TODO Auto-generated method stub 
      return super.instantiateItem(arg0, arg1); 
    } 
      
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) { 
      System.out.println( "position Destory" + position); 
      super.destroyItem(container, position, object); 
    } 
      
  } 
  
    
  /** 
   * 无状态的 会全部加载着, 这个适合少量的 特别多的图片啊啥的 还是用 FragmentStatePagerAdapter 
   * @author lilei 
   */
//  public static class MyAdapter extends FragmentPagerAdapter { 
//   public MyAdapter(FragmentManager fm ) { 
//      super(fm); 
//     
//    } 
// 
//    @Override 
//    public int getCount() { 
//      return NUM_ITEMS; 
//    } 
// 
//    @Override 
//    public Fragment getItem(int position) { 
//     // 返回相应的 fragment 
//      return ArrayFragment.newInstance(position); 
//    } 
//     
//    @Override 
//    public void destroyItem(ViewGroup container, int position, Object object) { 
//     System.out.println( "position Destory" + position); 
//     super.destroyItem(container, position, object); 
//    } 
//  } 
    
    
  /** 
   * 所有的 每个Fragment 
   */
  public static class ArrayFragment extends Fragment { 
      
    int mNum; 
    static ArrayFragment newInstance(int num) { 
      ArrayFragment array= new ArrayFragment(); 
      Bundle args = new Bundle(); 
      args.putInt("num", num); 
      array.setArguments(args); 
      return array; 
    } 
  
      
    @Override
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      mNum = getArguments() != null ? getArguments().getInt("num") : 1; 
      System.out.println("mNum Fragment create ="+ mNum); 
    } 
  
      
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) { 
       System.out.println("onCreateView = "); 
       //在这里加载每个 fragment的显示的 View 
       View v = null; 
         
       if(mNum == 0){ 
         v = inflater.inflate(R.layout.pagers_fragment1, container, false); 
         ((TextView)v.findViewById(R.id.textView1)).setText(mNum+ "= mNum");             
       }else if(mNum == 1){ 
         v = inflater.inflate(R.layout.pagers_fragment1, container, false); 
         ((TextView)v.findViewById(R.id.textView1)).setText(mNum+ "= mNum"); 
       }else if(mNum == 2){ 
         v = inflater.inflate(R.layout.pagers_fragment1, container, false); 
         ((TextView)v.findViewById(R.id.textView1)).setText(mNum+ "= mNum"); 
       }else{ 
         v = inflater.inflate(R.layout.pagers_fragment1, container, false); 
         ((TextView)v.findViewById(R.id.textView1)).setText(mNum+ "= mNum"); 
       }    
      return v; 
    } 
  
    @Override
    public void onActivityCreated(Bundle savedInstanceState) { 
      System.out.println("onActivityCreated = "); 
      super.onActivityCreated(savedInstanceState);   
    } 
      
    @Override
    public void onDestroyView(){ 
      System.out.println(mNum + "mNumDestory"); 
      super.onDestroyView(); 
    } 
      
    @Override
    public void onDestroy(){ 
      super.onDestroy();  
    } 
      
  } 
}
Copy after login

2. Nothing too much with 1 The big difference (the use depends on the individual)

public class ViewPageFragmentCS extends FragmentActivity { 
    
  //这个是有多少个 fragment页面 
  private MyAdapter  mAdapter; 
  private ViewPager  mPager;  
  private List<Entity> list = new ArrayList<ViewPageFragmentCS.Entity>();; 
  
  @Override
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.pagers_fragment_main); 
      
    for (int i = 0; i < 7 ; i++) { 
      Entity ee = new Entity(); 
      ee.name = "ll"+ i; 
      ee.age = ""+ i; 
      list.add(ee); 
    } 
    mAdapter = new MyAdapter(getSupportFragmentManager(),list); 
    mPager = (ViewPager)findViewById(R.id.mypagers_pager); 
    mPager.setAdapter(mAdapter); 
  } 
  
  
    
  private class Entity{ 
    public String name; 
    public String age; 
  } 
    
    
  // 在这里你可以传 list<Fragment> 也可以传递 list<Object>数据 
  public class MyAdapter extends FragmentStatePagerAdapter { 
    List<Entity> list_ee; 
      
    public MyAdapter(FragmentManager fm, List<Entity> ee) { 
      super(fm); 
      this.list_ee = ee ; 
    } 
  
    @Override
    public int getCount() { 
      return list_ee.size(); 
    } 
  
    // 初始化每个页卡选项 
    @Override
    public Object instantiateItem(ViewGroup arg0, int position) { 
        
      ArrayFragment ff = (ArrayFragment)super.instantiateItem(arg0, position); 
      ff.setThings(list_ee.get(position),position); 
      return ff; 
    } 
      
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) { 
      System.out.println( "position Destory" + position); 
      super.destroyItem(container, position, object); 
    } 
  
      
    @Override
    public Fragment getItem(int arg0) { 
      // TODO Auto-generated method stub 
      return new ArrayFragment(); 
    } 
      
  } 
  
    
    
  /** 
   * 所有的 每个Fragment 
   */
  public class ArrayFragment extends Fragment { 
    private Entity ee; 
    private int position; 
      
    public void setThings(Entity ee,int position){ 
      this.ee =ee ;   
      this.position = position; 
    } 
  
    @Override
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
    } 
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) { 
       System.out.println("onCreateView = "); 
       //在这里加载每个 fragment的显示的 View 
       View v = inflater.inflate(R.layout.pagers_fragment1, container, false); 
      ((TextView)v.findViewById(R.id.textView1)).setText(ee.name+ "= ee.Name -=age"+ ee.age);  
      return v; 
    } 
  
    @Override
    public void onActivityCreated(Bundle savedInstanceState) { 
      System.out.println("onActivityCreated = "); 
      super.onActivityCreated(savedInstanceState);   
    } 
      
    @Override
    public void onDestroyView(){ 
      System.out.println("onDestroyView = "+ position); 
      super.onDestroyView(); 
    } 
      
    @Override
    public void onDestroy(){ 
      System.out.println("onDestroy = "+ position); 
      super.onDestroy();  
    }     
  } 
}
Copy after login

Just copy it and you can see the effect. Don’t forget the V4 package. You can complete the xml layout file by yourself.
When you slide to the 3rd page, you can see that the 1st page is destroyed and the 4th one is generated. Currently, there are 2, 3, and 4:

Android App中使用ViewPager+Fragment实现滑动切换效果

More Android For related articles using ViewPager+Fragment in App to achieve sliding switching effect, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles