Collapsible View Pager With Indicators

Hello Friend, Here We again came with our another amazing android Development tutorial On how to implement collapsible View Pager with Circular indicators This can help in your app if you have to show some graphical ads on top of your screen to attract more User.
So, Come on Let's get Start,

First Of all, Create new Project

and Add this Dependencies
compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.android.support:cardview-v7:25.3.1' Is For Cardview compile 'com.android.support:recyclerview-v7:25.3.1' Is For RecyclerView compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' Is For Image Loader to Load image in View Pager with Progress bar This is Our Project Structure
Add this in dimen.xml

    250dp
    -64dp
    32dp
    0dp
    10dp
    10dp
    250dp
    15dp


Make a Layout file Named as content_main.xml  This file will contain our Recycler View which shows the List in GridLayout Add this code into it
<?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   app:layout_behavior="@string/appbar_scrolling_view_behavior"  
   tools:showIn="@layout/activity_main">  
   
   
   <android.support.v7.widget.RecyclerView  
     android:id="@+id/rv_keyword"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:clipToPadding="false"  
     android:scrollbars="vertical">  
   </android.support.v7.widget.RecyclerView>  
   
 </RelativeLayout&gt
Then Make a File name as tab_selector.xml in Drawable folder we use this file to customize our tab layout and make it in circular indicators
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
   
   
   <item android:drawable="@drawable/selected_dot"  
     android:state_selected="true"/>  
   
   <item android:drawable="@drawable/default_dot"/>  
   
 </selector>  

Open Your activity_main.xml and Add this code into it
<?xml version="1.0" encoding="utf-8"?>  
 <android.support.design.widget.CoordinatorLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:id="@+id/main_content"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:fitsSystemWindows="true"  
   tools:context="com.targetandroid.info.viewpageradds.MainActivity">  
   
   <android.support.design.widget.AppBarLayout  
   android:id="@+id/appbar"  
   android:layout_width="match_parent"  
   android:layout_height="@dimen/detail_backdrop_height"  
   android:fitsSystemWindows="true"  
   android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">  
   
   <android.support.design.widget.CollapsingToolbarLayout  
     android:id="@+id/collapsing_toolbar"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:fitsSystemWindows="true"  
     app:contentScrim="@color/colorPrimary"  
     app:expandedTitleMarginEnd="64dp"  
     app:expandedTitleMarginStart="48dp"  
     app:expandedTitleTextAppearance="@android:color/transparent"  
     app:layout_scrollFlags="scroll|exitUntilCollapsed">  
   
   
   
     <android.support.v4.view.ViewPager  
       android:id="@+id/vp_adds"  
       android:layout_width="match_parent"  
       android:layout_height="@dimen/detail_backdrop_height"  
       android:background="@color/colorPrimary"  
       android:layout_gravity="center_horizontal"  
       app:layout_collapseMode="parallax"  
       app:layout_behavior="@string/appbar_scrolling_view_behavior">  
   
     </android.support.v4.view.ViewPager>  
   
      <android.support.design.widget.TabLayout  
        android:id="@+id/tab_layout"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        app:tabGravity="center"  
        android:layout_below="@+id/toolbar"  
        android:layout_gravity="bottom"  
        app:tabBackground="@drawable/tab_selector"  
        app:tabIndicatorHeight="0dp"  
        />  
   
     <android.support.v7.widget.Toolbar  
       android:id="@+id/toolbar"  
       android:layout_width="match_parent"  
       android:layout_height="?attr/actionBarSize"  
       app:layout_collapseMode="parallax"  
       app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />  
   
     </android.support.design.widget.CollapsingToolbarLayout>  
   
    </android.support.design.widget.AppBarLayout>  
   
   
   <include layout="@layout/content_main"/>  
   
 </android.support.design.widget.CoordinatorLayout>  
Benefits Of Coordinator Layout from docs the Design library introduces CoordinatorLayout, a layout which provides an additional level of control over touch events between child views, something which many of the components in the Design library take advantage of. https://android-developers.googleblog.com/2015/05/android-design-support-library.html in this link, you will see the demo videos of all above-mentioned views. Now Create a layout file and Name it as custom_keywordlayout this file contains the code for how to display the single Keyword this layout will repeat for every Keyword If You want to Know more about Recycler view then you can check my previous blog post by clicking here  Recycler View add this code inside custom_keywordlayout
<?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical"  
   android:layout_width="wrap_content"  
   android:background="@color/album_background"  
   android:layout_height="wrap_content">  
   
   <android.support.v7.widget.CardView  
     android:id="@+id/historycard_view"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:layout_gravity="center"  
     android:layout_margin="@dimen/card_margin"  
     android:elevation="3dp"  
     android:background="@color/colorPrimary">  
   
     <RelativeLayout  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content">  
   
       <ImageView  
         android:id="@+id/keywordicon"  
         android:layout_width="match_parent"  
         android:layout_height="@dimen/album_cover_height"  
         android:background="?attr/selectableItemBackgroundBorderless"  
         android:clickable="true"  
         android:scaleType="fitXY"  
         />  
   
       <LinearLayout  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  
         android:orientation="horizontal"  
         android:gravity="center_vertical|center_horizontal|center"  
         android:layout_below="@id/keywordicon"  
         android:layout_alignParentBottom="true"  
         android:background="@color/colorwhite">  
         <TextView  
           android:id="@+id/keywordtitle"  
           android:layout_width="match_parent"  
           android:layout_height="wrap_content"  
           android:paddingLeft="@dimen/album_title_padding"  
           android:paddingRight="@dimen/album_title_padding"  
           android:paddingTop="@dimen/album_title_padding"  
           android:textColor="@color/keyword_title"  
           android:text=""  
           android:gravity="center"  
           android:layout_gravity="center_vertical|center"  
           android:textSize="@dimen/album_title" />  
   
       </LinearLayout>  
   
     </RelativeLayout>  
   
   </android.support.v7.widget.CardView>  
     
 </LinearLayout> 
Create two Singleton class and named it as Keywords.java and KeywordListAdapter.java the first class contains some Getter Setter Methods and the second one is the Custom Adapter for RecyclerView
/**
 * Created by Faizan on 22-05-17.
 */

public class Keywords
{

    private int thumbnail;
    private String keyname;

    public Keywords(int thumbnail, String keyname) {
        this.thumbnail = thumbnail;
        this.keyname = keyname;
    }


    public int getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(int thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getKeyname() {
        return keyname;
    }

    public void setKeyname(String keyname) {
        this.keyname = keyname;
    }
}


import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Faizan on 22-05-17.
 */

public class KeywordListAdapter extends RecyclerView.Adapter {

    private Context context;
    private List keywordList=new ArrayList<>();

    public KeywordListAdapter(Context context, List keywordList) {
        this.context = context;
        this.keywordList = keywordList;
    }

    @Override
    public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_keywordlayout,parent,false);

        MyviewHolder myviewHolder=new MyviewHolder(itemView);

        return myviewHolder;
    }

    @Override
    public void onBindViewHolder(MyviewHolder holder, int position) {

        Keywords keyword = keywordList.get(position);
        holder.keywordtitle.setText(keyword.getKeyname());
        holder.keywordicon.setImageResource(keyword.getThumbnail());
    }

    @Override
    public int getItemCount() {
        return keywordList==null?0:keywordList.size();
    }

    public class MyviewHolder extends RecyclerView.ViewHolder
    {
        public TextView keywordtitle;
        public ImageView keywordicon;
        public CardView historycard_view;

        public MyviewHolder(View itemView) {
            super(itemView);

            keywordtitle=(TextView)itemView.findViewById(R.id.keywordtitle);
            keywordicon=(ImageView)itemView.findViewById(R.id.keywordicon);
            historycard_view=(CardView)itemView.findViewById(R.id.historycard_view);


        }
    }
}

To Know More About adapter and POJO class Visit my previous Post FromHere Create a Fragment (Blank)  For View Pager on which we will display the images and which will change by sliding the view pager I have a made a Fragment with name ViewPagerAddsFragment.java After creating Fragment you will get two files one of that is JAVA and the Second one is XML So in XML write below code which contains Progress bar because we have to display progress bar till the image is not properly loaded using ImageLoader.
<FrameLayout 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.targetandroid.info.viewpageradds.ViewPagerAddsFragment">  
   
   <ImageView  
     android:id="@+id/iv_adds"  
     android:layout_width="match_parent"  
     android:layout_height="@dimen/detail_backdrop_height"  
     android:scaleType="fitXY"  
     android:layout_alignParentTop="true"  
     android:elevation="10dp"  
     />  
   
   <ProgressBar  
     android:id="@+id/pb_addsprogressBar"  
     style="?android:attr/progressBarStyleLarge"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:visibility="visible"  
     android:layout_gravity="center_horizontal"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="70dp"  
     >  
   </ProgressBar>  
   
 </FrameLayout> 

and in ViewPagerAddsFragment.java  we are Using Image Loader the Syntax for imageLoader is
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) // You can pass your own memory cache implementation .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .build(); DisplayImageOptions options = new DisplayImageOptions.Builder() .displayer(new RoundedBitmapDisplayer(10))//rounded corner bitmap .cacheInMemory(true) .cacheOnDisk(true) .build(); ImageLoader imageLoader = ImageLoader.getInstance(); imageLoader.init(config); imageLoader.setDefaultLoadingListener(new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { } @Override public void onLoadingCancelled(String imageUri, View view) { } });
If you want to do something before loading the image For Example Show Some kind of loader or Progress bar then write that code inside  public void onLoadingStarted If Loading of Image Gets Failed Due to some Reason then you can show the Reason in public void onLoadingFailed public void onLoadingComplete Execute after image gets load completely public void onLoadingCancelled Execute if loading of the image is getting's canceled by some factors This is The Full Code of ViewPagerAddsFragment.java
package com.targetandroid.info.viewpageradds;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;


public class ViewPagerAddsFragment extends Fragment {
    
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private int mParam1;
    private String mParam2;

    //Declaration of View Present in layout file
    ImageView iv_adds;
    ProgressBar pb_addsprogressBar;

    public ViewPagerAddsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ViewPagerAddsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ViewPagerAddsFragment newInstance(int param1, String param2) {
        ViewPagerAddsFragment fragment = new ViewPagerAddsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_view_pager_adds, container, false);



        iv_adds=(ImageView)view.findViewById(R.id.iv_adds);
        pb_addsprogressBar=(ProgressBar)view.findViewById(R.id.pb_addsprogressBar);

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext())
                // You can pass your own memory cache implementation
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .build();

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .displayer(new RoundedBitmapDisplayer(10))//rounded corner bitmap
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);
        imageLoader.setDefaultLoadingListener(new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                pb_addsprogressBar.setVisibility(View.VISIBLE);//when loading started progress bar will Visible
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason)
            {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                pb_addsprogressBar.setVisibility(View.GONE);//when loading Completed progress bar will Disappear
                pb_addsprogressBar.destroyDrawingCache();
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
            }
        });

        imageLoader.displayImage(mParam2,iv_adds,options );//set the fetched image to imageview with round corner


       // iv_adds.setImageResource(mParam1);

        return view;
    }

}
Now Finally Come Towards the MainActivity.java I have Already explained every part of the code in comments So, I hope you will not face any Confusion.
package com.targetandroid.info.viewpageradds;

import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager vp_adds;
    private Toolbar toolbar;
    private CollapsingToolbarLayout collapsingToolbar;
    List keywordList;
    private RecyclerView rv_keyword;
    private KeywordListAdapter keywordListAdapter;

    private static final String TAG = MainActivity.class.getSimpleName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setSupportActionBar(toolbar);

        toolbar=(Toolbar)findViewById(R.id.toolbar);
        vp_adds=(ViewPager)findViewById(R.id.vp_adds);
        rv_keyword=(RecyclerView)findViewById(R.id.rv_keyword);
        collapsingToolbar =(CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);


       // ((AppCompatActivity) MainActivity.this).getSupportActionBar().setTitle("Dashboard");

        keywordList=new ArrayList<>();

        //calling collapsible method in oncreate
        initCollapsingToolbar();


        //setting adpater in viewpager
        vp_adds.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

        //margin to dispaly two page at one time like GoogleplayStore
        //vp_adds.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.viewpager_margin));
        //vp_adds.setDrawingCacheEnabled(true);


        //Cicular Indicator for Viewpager
        TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(vp_adds, true);


        //Setting Recyclerview LayoutManager
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(MainActivity.this, 2);
        rv_keyword.setLayoutManager(mLayoutManager);

        //Calling method to set content on recyclerview
        prepareKeyword();

    }


    /*
    * Send the Url of image which we want to display in view pager
     * to fragment to set on imageview
    * */

    private class ViewPagerAdapter extends FragmentStatePagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment=ViewPagerAddsFragment.newInstance(R.mipmap.ic_launcher,"Intialize");

            switch (position)
            {

                case 0:
                    fragment=ViewPagerAddsFragment.newInstance(R.mipmap.ic_launcher,"http://imgs.abduzeedo.com/files/paul0v2/footwear-ads/ADIDAS_TREE.preview.jpg");
                    break;
                case 1:
                    fragment=ViewPagerAddsFragment.newInstance(R.mipmap.ic_launcher,"http://www.sourceraven.com/wp-content/uploads/2014/01/creative1.png");
                    break;
                case 2:
                    fragment=ViewPagerAddsFragment.newInstance(R.mipmap.ic_launcher,"http://pixelantix.com/img/slider/Creative-Design-Business.jpg");
                    break;
                default:
                    fragment=ViewPagerAddsFragment.newInstance(R.mipmap.ic_launcher,"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMp-NDP9XDCheIQMSbOruCY-k3zKgpjLS14HzmyKiXg7lbBdKfoIZxrTmjh2o_I9801p7J9KORUaixHuJIgowCO1g0FgsqX0r6xjqAh2uzpOv-DZFeSEfF6VEEisZMGwMuWZupiXpuI8c/s1600/funadress+creative+drawings+9.jpg");
                    break;

            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }



/*
* Set the Content on Recycler view , icon and Title
*
* */
    private void prepareKeyword() {

        int[] keywordicon = new int[]{
                R.mipmap.glitterbug,
                R.mipmap.colorface,
                R.mipmap.goblin,
                R.mipmap.girls,
                R.mipmap.blueneighbour,
                R.mipmap.magdalena,
                /*R.mipmap.keyword7,
                R.mipmap.keyword8,
                R.mipmap.keyword9,*/
                };
        keywordList.add(new Keywords(keywordicon[0],"Glitter Bug"));
        keywordList.add(new Keywords(keywordicon[1],"Color Face"));
        keywordList.add(new Keywords(keywordicon[2],"Goblin"));
        keywordList.add(new Keywords(keywordicon[3],"Girls"));
        keywordList.add(new Keywords(keywordicon[4],"Blue Neighbour"));
        keywordList.add(new Keywords(keywordicon[5],"Magdalena"));
       /* keywordList.add(new Keywords(keywordicon[6],"TV"));
        keywordList.add(new Keywords(keywordicon[7],"Heater"));
        keywordList.add(new Keywords(keywordicon[8],"Microwave"));*/


        keywordListAdapter=new KeywordListAdapter(MainActivity.this,keywordList);
        rv_keyword.setAdapter(keywordListAdapter);



    }


    /**
     *
     * Will show and hide the toolbar title on scroll
     */
    private void initCollapsingToolbar() {

       collapsingToolbar.setTitle("");
        AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appbar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0)
                {
                    collapsingToolbar.setTitle("Dashboard");
                    isShow = true;
                } else if (isShow) {
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                }
            }
        });
    }

}

Now Compile Your Project You Will Find This as an Output
 
For More Tutorial Subscribe to my Blog So you will get all the updates on your email, We Never Spam Thank You
SHARE

Faizan Sayyed

  • Image
  • Image
  • Image
  • Image
  • Image

0 comments:

Post a Comment