ViewPager的简单学习

作者: Karma1026 | 来源:发表于2016-03-17 10:44 被阅读189次

    Android官方滑动控件ViewPager学习

    这几天看到了很多APP在顶部都有滚播功能的,然后了解了一下它的实现原理,发现是用官方ViewPager控件实现的,所以就去看了官方的API文档去了解学习

    ** 官方文档 **
    Class Overview
    Base class providing the adapter to populate pages inside of a ViewPager. You will most likely want to use a more specific implementation of this, such as FragmentPagerAdapter orFragmentStatePagerAdapter.

    When you implement a PagerAdapter, you must override the following methods at minimum:

    instantiateItem(ViewGroup, int)
    destroyItem(ViewGroup, int, Object)
    getCount()
    isViewFromObject(View, Object)
    

    PagerAdapter is more general than the adapters used for AdapterViews. Instead of providing a View recycling mechanism directly ViewPager uses callbacks to indicate the steps taken during an update. A PagerAdapter may implement a form of View recycling if desired or use a more sophisticated method of managing page Views such as Fragment transactions where each page is represented by its own Fragment.

    ViewPager associates each page with a key Object instead of working with Views directly. This key is used to track and uniquely identify a given page independent of its position in the adapter. A call to the PagerAdapter method startUpdate(ViewGroup) indicates that the contents of the ViewPager are about to change. One or more calls to instantiateItem(ViewGroup, int) and/ordestroyItem(ViewGroup, int, Object) will follow, and the end of an update will be signaled by a call to finishUpdate(ViewGroup). By the time finishUpdate returns the views associated with the key objects returned by instantiateItem should be added to the parent ViewGroup passed to these methods and the views associated with the keys passed to destroyItem should be removed. The method isViewFromObject(View, Object) identifies whether a page View is associated with a given key object.

    A very simple PagerAdapter may choose to use the page Views themselves as key objects, returning them from instantiateItem(ViewGroup, int) after creation and adding them to the parent ViewGroup. A matching destroyItem(ViewGroup, int, Object) implementation would remove the View from the parent ViewGroup and isViewFromObject(View, Object) could be implemented as return view == object;.

    PagerAdapter supports data set changes. Data set changes must occur on the main thread and must end with a call to notifyDataSetChanged() similar to AdapterView adapters derived fromBaseAdapter. A data set change may involve pages being added, removed, or changing position. The ViewPager will keep the current page active provided the adapter implements the methodgetItemPosition(Object).

    其实很多英文单词我们都认识,大概知道他讲什么意思,我们不需要全部看完,只要知道他要用到适配器,然后重写上面那四个方法就好了。
    步骤:
    • 在主布局文件里加入ViewPager这个控件
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.kevin.viewpagertest_1.MainActivity">
    
        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"></android.support.v4.view.ViewPager>
    </RelativeLayout>
    
    • 我们新建三个layout来作为切换的视图
      1.layout_1.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="#e10c0c"
       android:orientation="vertical">
    </LinearLayout>
    

    2.layout_2.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="#14dc1e"
       android:orientation="vertical">
    </LinearLayout>
    

    3.layout_3.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="#d96308"
       android:orientation="vertical">
    </LinearLayout>
    
    • MainActivity代码
    package com.example.kevin.viewpagertest_1;
    
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
        private View view1;
        private View view2;
        private View view3;
        private ViewPager viewPager;
        private List<View> viewList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
            initData();
        }
    
        private void initView() {
            LayoutInflater inflater = getLayoutInflater();
            view1 = inflater.inflate(R.layout.layout_1, null);
            view2 = inflater.inflate(R.layout.layout_2, null);
            view3 = inflater.inflate(R.layout.layout_3, null);
            viewPager = (ViewPager) findViewById(R.id.viewPager);
            viewList = new ArrayList<View>();
        }
    
        private void initData() {
            viewList.add(view1);
            viewList.add(view2);
            viewList.add(view3);
            viewPager.setAdapter(pagerAdapter);
        }
        //适配器
        private PagerAdapter pagerAdapter = new PagerAdapter() {
            //返回当前视图的个数
            @Override
            public int getCount() {
                return viewList.size();
            }
    
            /**
             * 功能:该函数用来判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是代表的同一个视图(即它俩是否是对应的,对应的表示同一个View)
             *返回值:如果对应的是同一个View,返回True,否则返回False。
             * @param view
             * @param object
             * @return
             */
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
                //return view == viewList.get((int) Integer.parseInt(object.toString()));
            }
    
            //移除当前某个视图
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewList.get(position));
            }
    
            /**
             * 在这里,我们做了两件事
             *第一:将参数里给定的position的视图,增加到conatiner中,供其创建并显示、。
             * 第二:返回当前position的View做为此视图的Key。
             * @param container
             * @param position
             * @return
             */
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewList.get(position));
                return viewList.get(position);
                //return position;
            }
        };
    }
    
    大概就完成了基本功能,需要更深入的了解,请看官方文档:Android开发者API文档链接---->自备梯子

    相关文章

      网友评论

        本文标题:ViewPager的简单学习

        本文链接:https://www.haomeiwen.com/subject/rehclttx.html