Saturday, September 12, 2015

How to Create a Horizontal Carousel View in Android (Using ViewPager)

Hello,

Recently in one of my project we have to create  Horizontal Carousel View for banner images. User can swipe left or right to view other banners and there will be bottom page indicators. See the below image of final output.


In this blog I am going to explain how to create horizontal carousel view. We are going to use Android ViewPager for this. First add following to layout XML.

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="120dp" />
     
     <LinearLayout
     android:layout_width="fill_parent"
     android:id="@+id/pagination"
     android:layout_height="15dp"
     android:background="#443915"
     android:orientation="horizontal" 
     android:gravity="center">
    </LinearLayout>

In android view page we will have different fragments for each page so we will need layout XML for fragment. Add new XML file myfragment_layout.xml in your layout and add following code to it.

<?xml version="1.0" encoding="utf-8"?>
      <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY"

        android:id="@+id/imageView" />

Now let's create fragments for each images.

List fList = new ArrayList();
List bannerList = getAllBanners(); 
LinearLayout pagination = (LinearLayout)rootView.findViewById(R.id.pagination);

getAllBanners () is the function I used my code, you can replace it with your logic.
pagination is the linear layout we added in XML above.

Now first create a linear layout to hold all the indicators.

LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.HORIZONTAL);

for(int i=0;i
          fList.add(new MyFragment().newInstance(bannerList.get(i).getPicName()));
          ImageView imageView = new ImageView(getActivity());
          if(i == 0){
              imageView.setImageResource(R.drawable.activeindicators);
          }else{
              imageView.setImageResource(R.drawable.inactiveindicators);
          }
          imageView.setId(i);
          LayoutParams params =new LayoutParams(LayoutParams.WRAP_CONTENT,     LayoutParams.WRAP_CONTENT);
          imageView.setLayoutParams(params);
          layout.addView(imageView);
}

pagination.addView(layout);

As you can in above code we are adding indicators in pagination and adding fragments to fragment list. By default we are setting first indicator as active.

Now to create Fragment we have to add MyFragment class.

public class MyFragment extends Fragment {
    public static final String EXTRA_MESSAGE = "PICTURE";
    public final MyFragment newInstance(String picName){
      MyFragment f = new MyFragment();
      Bundle bdl = new Bundle(1);
      bdl.putString(EXTRA_MESSAGE, picName);
      f.setArguments(bdl);
      return f;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      String picName = getArguments().getString(EXTRA_MESSAGE);
      View v = inflater.inflate(R.layout.myfragment_layout, container, false);
      ImageView messageTextView = (ImageView)v.findViewById(R.id.imageView);
      int id = getResources().getIdentifier("yourpackagename:drawable/" + picName, null, null);
      v.setImageResource(id);
      return v;
    }
}

Now lets's create Adapter for ViewPager. 

MyPageAdapter  pageAdapter = new MyPageAdapter(getActivity().getSupportFragmentManager(), fList);
ViewPager pager =(ViewPager)rootView.findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);

For that we have to create MyPageAdapter

class MyPageAdapter extends FragmentPagerAdapter {
      private List fragments;
      public MyPageAdapter(FragmentManager fm, List fragments) {
        super(fm);
        this.fragments = fragments;
      }
      @Override 
      public Fragment getItem(int position) {
        return this.fragments.get(position);
      }
      @Override
      public int getCount() {
        return this.fragments.size();
      }
 }

This will create number of fragments as per your number. Now we have to add logic to change page indicators when user swipe left or right.

pager.setOnPageChangeListener(new OnPageChangeListener() {
  @Override
   public void onPageSelected(int position) {
   // TODO Auto-generated method stub
        for(int i=0 ;i<totalBannerCount;i++){
        ImageView img = (ImageView)rootView.findViewById(i);
        if(i== position){
            img.setImageResource(R.drawable.activeindicators);
        }else{
            img.setImageResource(R.drawable.inactiveindicators);
        }
    }
}
  @Override
   public void onPageScrolled(int arg0, float arg1, int arg2) {
      // TODO Auto-generated method stub
   }
   @Override
    public void onPageScrollStateChanged(int arg0) {
    // TODO Auto-generated method stub
    }
});

That's it and you have Horizontal Carousel View in Android. Hope this helps you.

1 comment:

  1. Can you review your Code, There is incomplete For loop " for(int i=0;i "

    ReplyDelete