#Android Learning# Realization of a simple carousel map [Part 1]

I have been learning Android for a while. I started writing Android programs at the beginning of my sophomore year. At that time, I really knew nothing, except that I had some Java foundation. Fortunately, I am grateful to myself for insisting on it. Now I can also write some Android applets by myself; now, haha, there are still a few days, oh, three days, I am a junior student, and in the junior year, I will learn Android more systematically Knowledge, choose to use time to settle yourself, of course, I will organize the knowledge I have learned into a blog, after all, I feel that I prefer to write things, haha...

Android carousels can be seen in many scenes, and they have many features:
- With indicators
- Each picture has a title
- You can manually slide left or right
- Automatically slide

The effect is as shown below

Peek 2017-08-28 20-10

code implementation logic

1. Add the layout in the .xml file

The layout components of this carousel box in the .xml file are quite simple, so I will directly upload the code. If you have an Android foundation, it should not be difficult to understand;

“`xml

2. Get the corresponding component in the MainActivity file

We need to get the ViewPager and the components in the gray LieanerLayout so that we can fill the components later;

This is also directly on the code:

/*
    * 初始化组件
    * */
    public void initView(){
        viewPager = (ViewPager) findViewById(R.id.viewPager);//用于填充图片
        title = (TextView) findViewById(R.id.content);//用于填充标题
        point = (LinearLayout) findViewById(R.id.pointViews);//用于填充指示器原点
    }

3. Fill the empty carousel box with data

  • First, prepare more than three pictures, preferably five. The large number is conducive to debugging and drawing experimental conclusions; put the prepared pictures under the following package path:

    package path

  • The first thing to do now is to fill the picture and display it on ViewPager. To display data in ViewPager, we need to inherit and implement an abstract class of PageAdapter. It is introduced in the source code of PagerAdapter that if we implement this class, we must implement the following four important methods;

    private class MyAdapter extends PagerAdapter{
          
          
            //返回需要显示的 view 个数
            @Override
            public int getCount() {
                return 0;
            }
    
            //返回 view 复用的规则
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return false;
            }
    
            //返回需要展示的 view
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                return super.instantiateItem(container, position);
            }
    
            //销毁已经展示的 view
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }
        }
    • The first getCount() method can be found in the general Adapter class, and its function is mainly to obtain the total number of Views that need to be displayed on the ViewPager;
    • The second method isViewFromObject(View view, Object object) is more important because it returns the rule of view reuse; to understand how this method reuses ViewPager, you need to go back to its source code:

      /**
      * Determines whether a page View is associated with a specific key object
      * as returned by {@link #instantiateItem(ViewGroup, int)}. This method is
      * required for a PagerAdapter to function properly.
      *
      * @param view Page View to check for association with <code>object</code>
      * @param object Object to check for association with <code>view</code>
      * @return true if <code>view</code> is associated with the key object <code>object</code>
      */
      public abstract boolean isViewFromObject(View view, Object object);

      The source code introduces that the method isViewFromObject() is used to determine whether the Page View displayed in the current carousel frame is the same as the Object returned by the method instantiateItem(ViewGroup, int), and it is judged that the Page View is the same as the Object through a special key of their own , when the respective two keys are the same, the corresponding page view can be displayed on the viewPage;

    • The third method instantiateItem(ViewGroup container, int position) is mainly used to add a view (to be displayed) into the ViewGroup container, and return the Object object containing the View;

    • The fourth method destroyItem(ViewGroup container, int position, Object object) is also more important. Its main function is to remove the View that has been displayed in the ViewGroup. If the View that has been displayed is not removed immediately, the program will Crashed; when the instantiateItem(ViewGroup container, int position) method puts back an Object, ViewPager uses this as the View for display;

  • Now you need to fill MyAdapter with data for display. First of all, we should get the resource ID of the image, and use these image resource IDs to create ImageView objects for display, and then load these ImageView objects into the List for easy filling into MyAdapter; the code is as follows:

    /**
     * 初始化数据
     */
    public void initData() {
        //获取图片的id
        imageId = new int[]{R.mipmap.a, R.mipmap.b, R.mipmap.c, R.mipmap.d, R.mipmap.e};
    
        //把 mImageView 装在 mImageViewList列表里面;
        for (int i = 0; i < imageId.length; i++) {
            mImageView = new ImageView(this);
            mImageView.setBackgroundResource(imageId[i]);
    
            mImageViewList.add(mImageView);
        }
    }
  • Now that you have the data, you can fill in the data in MyAdpter. The logic is as follows:

    private class MyAdapter extends PagerAdapter {
          
          
    
        //返回需要显示的 view 个数
        @Override
        public int getCount() {
            return mImageViewList.size();
        }
    
        //返回 view 复用的规则
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    
        //返回需要展示的 view
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int newPosition = position % mImageViewList.size();
            ImageView imageView = mImageViewList.get(newPosition);
            container.addView(imageView);
    
            return imageView;
        }
    
        //销毁已经展示的 view
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //Log.d("测试destroyItem里面的 object", "destroyItem: " + object);
            container.removeView((View)object);
        }
    }
  • Then load the above MyAdapter into it through the setAdapter() method of viewPager:

    /**
     * 配置 viewPager
     */
    public void initMyAdapter(){
        viewPager.setAdapter(new MyAdapter());
    }
  • Through the above code logic, we can get the following rendering:
    Semi-finished product renderings

Summary
At present, we have realized filling pictures into ViewPager, and then my next blog post will bring in each View with indicators and titles, and the effect of indicators and titles moving with pictures, thank you for your support read…

Guess you like

Origin blog.csdn.net/HongHua_bai/article/details/77840300