Carousel view in Android

Hello Guys !!!

Hope you all doing well...

In this tutorial, you will learn how to implement a carousel in your Android application.  

Here is necessary java classes and xml files.

1. MainActivity.java

package com.pack.carousel;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;

public class MainActivity extends FragmentActivity {
public final static int LOOPS = 1000;
public static int FIRST_PAGE; // = count * LOOPS / 2;
public final static float BIG_SCALE = 1.0f;
public final static float SMALL_SCALE = 0.7f;
public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
public MyPagerAdapter adapter;
public ViewPager pager;
/*** variables for the View */
public int coverUrl[];
public static int count;

public static MainActivity mainActivityCtx;

public static int currentPage = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

coverUrl = new int[] { R.drawable.images11, R.drawable.images23,
R.drawable.images3, R.drawable.images33, R.drawable.images4,
R.drawable.images44, R.drawable.images5, R.drawable.images66,
R.drawable.images7, R.drawable.images8 };

mainActivityCtx = this;
pager = (ViewPager) findViewById(R.id.myviewpager);
count = coverUrl.length;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int pageMargin = 0;
pageMargin = (int) ((metrics.widthPixels / 4) *2);
pager.setPageMargin(-pageMargin);

try {
adapter = new MyPagerAdapter(this, this.getSupportFragmentManager());
pager.setAdapter(adapter);
adapter.notifyDataSetChanged();

FIRST_PAGE = count * LOOPS / 2;

pager.setOnPageChangeListener(adapter);
// Set current item to the middle page so we can fling to both
// directions left and right
pager.setCurrentItem(FIRST_PAGE); // FIRST_PAGE
// pager.setFocusableInTouchMode(true);
pager.setOffscreenPageLimit(3);
// Set margin for pages as a negative number, so a part of next and
// previous pages will be showed

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

}


2. MyFragment.java

package com.pack.carousel;

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.LinearLayout;
import android.widget.TextView;

public class MyFragment extends Fragment {
public static Fragment newInstance(MainActivity context, int pos, float scale) {
Bundle b = new Bundle();
b.putInt("pos", pos);
b.putFloat("scale", scale);
return Fragment.instantiate(context, MyFragment.class.getName(), b);
}

@Override             
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
 
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(400,400);
LinearLayout fragmentLL  = (LinearLayout) inflater.inflate(R.layout.mf, container, false);
int pos = this.getArguments().getInt("pos");
TextView tv = (TextView) fragmentLL.findViewById(R.id.text);
 
tv.setText("Image " +  pos );
 
ImageView iv = (ImageView) fragmentLL.findViewById(R.id.pagerImg);

iv.setLayoutParams(layoutParams);
iv.setImageResource(MainActivity.mainActivityCtx.coverUrl[pos] );
iv.setPadding(15, 15, 15, 15);

MyLinearLayout root = (MyLinearLayout) fragmentLL.findViewById(R.id.root);
float scale = this.getArguments().getFloat("scale");
root.setScaleBoth(scale);

return fragmentLL;
}
}

3. MyLinearLayout.java

package com.pack.carousel;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class MyLinearLayout extends LinearLayout {
private float scale = MainActivity.BIG_SCALE;

public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyLinearLayout(Context context) {
super(context);
}

public void setScaleBoth(float scale) {
this.scale = scale;
this.invalidate();
 
}

@Override
protected void onDraw(Canvas canvas) {
// The main mechanism to display scale animation, you can customize it as your needs
int w = this.getWidth();
int h = this.getHeight();
canvas.scale(scale, scale, w/2, h/2);

super.onDraw(canvas);
}

}

4. MyPagerAdapter.java

package com.pack.carousel;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MyPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {

private MyLinearLayout cur = null;
private MyLinearLayout next = null;
private MainActivity context;
private FragmentManager fm;
private float scale;
int pCount = 0;
public MyPagerAdapter(MainActivity context, FragmentManager fm) {
super(fm);
this.fm = fm;
this.context = context;
}

@Override
public Fragment getItem(int position) {
// make the first pager bigger than others
try {
if (position == MainActivity.FIRST_PAGE)
scale = MainActivity.BIG_SCALE;    
else
scale = MainActivity.SMALL_SCALE;

position = position % MainActivity.count;

} catch (Exception e) {
// TODO: handle exception
}
return MyFragment.newInstance(context, position, scale);
}

@Override
public int getCount() {
int count = 0;
try {
 count = MainActivity.count * MainActivity.LOOPS;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return  count  ;   
}

@Override
public void onPageScrolled( int position, float positionOffset, int positionOffsetPixels){
try {
if (positionOffset >= 0f && positionOffset <= 1f) {
cur = getRootView( position );
next = getRootView( position +1 );

cur.setScaleBoth(MainActivity.BIG_SCALE   - MainActivity.DIFF_SCALE * positionOffset);
next.setScaleBoth(MainActivity.SMALL_SCALE  + MainActivity.DIFF_SCALE * positionOffset);

pCount++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {

}

private MyLinearLayout getRootView(int position) {
return (MyLinearLayout) fm.findFragmentByTag(this.getFragmentTag(position)).getView().findViewById(R.id.root);
}

private String getFragmentTag(int position) {
return "android:switcher:" + context.pager.getId() + ":" + position;
}
}


Here are the xml files

1. activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <android.support.v4.view.ViewPager
        android:id="@+id/myviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:overScrollMode="never" />

</LinearLayout>

2. mf.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:gravity="center"
    android:orientation="vertical" >

    <com.pack.carousel.MyLinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/pagerImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textColor="#000"
            android:textSize="20dp" />
    </com.pack.carousel.MyLinearLayout>

</LinearLayout>


Here is the output of the program..







Happy Coading !!


Comments

  1. I need to show elements back to the 3 images. For example, if I have 5 elements in my view, I need to show 3 on the front and 2 on the back, how can I do it?

    ReplyDelete
  2. i need full source code o this project.where i purchase

    ReplyDelete
  3. By default in view we can able to see only 3 images but i tried to change to 6 to 7 images in view can't able to do it can you please help out for this issue.

    ReplyDelete
  4. Hi this is of great help but can you guide me for logic if in case I have to blur the images on the sides for example the image in centre should be zoomed n sides to be blurred

    ReplyDelete

Post a Comment

Popular posts from this blog

Get Phone Contacts and display in Listview in Android

Draw Pie Chart using Canvas and Third party Library in Android