Curve Gallery View(Carousel) into Android.

Android (Carousel) Gallery View - The Gallery is a view that shows images in a center-locked. Android Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center in Gallery View.


Create New Project

1. First create a new project in Android Studio (File => New Project)
2. Open activity_main.xml and Add below code.

activity_main.xml

									   
   <?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageshow"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".7"
        android:scaleType="fitXY" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".3">

        <com.narendra.gallery.CarveGallery
            android:id="@+id/galleryshow"
            android:layout_centerInParent="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight=".4"
            android:spacing="3dp" />
    </RelativeLayout>
</LinearLayout>

Create a new xml file in values (res->values->attributes.xml)


attributes.xml

									   
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<declare-styleable name="Gallery1">
	<attr name="android:galleryItemBackground"/>
	</declare-styleable>
</resources>

Create a new Java file and add below code.


CarveGallery.java


package com.narendra.gallery;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Gallery;
import android.widget.SpinnerAdapter;

public class CarveGallery extends Gallery{

    private static final float INITIAL_MINOR_RATIO = 0.75f;
    private static final float INITIAL_MAJOR_RATIO = 0.75f;

    private int mEllipseMajor;
    private int mEllipseMinor;
    private int mEllipseMajor2;
    private int mEllipseMinor2;
    private int mEllipseYOffset;

    private Animation mGalleryAlphaOut;
    private Animation mGalleryAlphaIn;

    private OnAnimationEndListener mFadeInEndListener;
    private OnAnimationEndListener mFadeOutEndListener;

    private boolean mCustomEllipseDim = false;

    private boolean mInfinite = true;

    private int mXOff = 0;

    private Animation.AnimationListener mFadeInAnimationListener = new Animation.AnimationListener() {
        public void onAnimationStart(Animation animation) {}
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationEnd(Animation animation) {
            if( mFadeInEndListener != null )
            {
                mFadeInEndListener.onAnimationEnd();
            }
        }
    };

    private Animation.AnimationListener mFadeOutAnimationListener = new Animation.AnimationListener() {
        public void onAnimationStart(Animation animation) {}
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationEnd(Animation animation) {
            if( mFadeOutEndListener != null )
            {
                mFadeOutEndListener.onAnimationEnd();
            }
        }
    };

    public CarveGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

    public CarveGallery(Context context) {
        super(context);
        init();
    }

    private void init()
    {
        setHorizontalFadingEdgeEnabled(false);
        setCallbackDuringFling(true);
        setUnselectedAlpha(1.0f);
        setHapticFeedbackEnabled(false);

        int dur = 5000;

        mGalleryAlphaOut = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_out);
        mGalleryAlphaOut.setFillAfter(true);
        mGalleryAlphaOut.setDuration(dur);
        mGalleryAlphaOut.setAnimationListener(mFadeOutAnimationListener);
        mGalleryAlphaIn = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);
        mGalleryAlphaIn.setFillAfter(true);
        mGalleryAlphaIn.setDuration(dur);
        mGalleryAlphaIn.setAnimationListener(mFadeInAnimationListener);
    }

    public int getEllipseMajor() {
        return mEllipseMajor;
    }

    public void setEllipseMajor(int ellipseMajor) {
        if( ellipseMajor == 0 )
        {
            mCustomEllipseDim = false;
        }
        this.mEllipseMajor = ellipseMajor;
    }

    public int getEllipseMinor() {
        return mEllipseMinor;
    }

    public void setEllipseMinor(int ellipseMinor) {
        if( ellipseMinor == 0 )
        {
            mCustomEllipseDim = false;
        }
        this.mEllipseMinor = ellipseMinor;
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        final int left = child.getLeft();
        final int childWidth = child.getWidth();
        final int childHeight = child.getHeight();

        int adjustedXOrigin = left - mXOff + (childWidth>>1);

        int newtop = (int) (mEllipseYOffset - Math.sqrt( mEllipseMinor2 * (1 - ((Math.pow(adjustedXOrigin, 2)) / mEllipseMajor2))));
        newtop -= (childHeight>>1);

        if( newtop >= 0 )
        {
            child.layout(left, newtop, left + childWidth, newtop + childHeight);
            return super.drawChild(canvas, child, drawingTime);
        }
        return true;
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if( !mCustomEllipseDim )
        {
            mEllipseMajor = (int) (getMeasuredWidth() * INITIAL_MAJOR_RATIO + 5.5f);
            mEllipseMinor = (int) (getMeasuredHeight() * INITIAL_MINOR_RATIO + 3.5f);
            mEllipseMajor2 = (int) Math.pow( mEllipseMajor, 2 );
            mEllipseMinor2 = (int) Math.pow( mEllipseMinor, 2 );
        }
        mEllipseYOffset = getMeasuredHeight() + (mEllipseMinor - (getMeasuredHeight() / 2));

        mXOff = (getWidth() / 2);
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {
        super.setAdapter(adapter);
        if( mInfinite )
        {
        }
    }

    public OnAnimationEndListener getFadeInEndListener() {
        return mFadeInEndListener;
    }

    public void setFadeInEndListener(OnAnimationEndListener fadeInEndListener) {
        this.mFadeInEndListener = fadeInEndListener;
    }

    public OnAnimationEndListener getFadeOutEndListener() {
        return mFadeOutEndListener;
    }

    public void setFadeOutEndListener(OnAnimationEndListener fadeOutEndListener) {
        this.mFadeOutEndListener = fadeOutEndListener;
    }

    public void fadeIn()
    {
        startAnimation(mGalleryAlphaIn);
    }

    public void fadeOut()
    {
        startAnimation(mGalleryAlphaOut);
    }

    public interface OnAnimationEndListener
    {
        public abstract void onAnimationEnd();
    }

    //This disables the effect of a vehicle becoming focused when it is clicked.
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        if( getAdapter() != null )
        {
            if( pointToPosition((int)e.getX(), (int)e.getY()) != getSelectedItemPosition() )
                return super.onSingleTapUp(e);
            else
                return true;
        }
        else
            return true;
    }
}
	

Create a new Java file. Implement with onTouchListener and also use GestureDetector.


OnSwipeTouchListener.java

									   
package com.narendra.gallery;

import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context ctx) {
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 1;
        private static final int SWIPE_VELOCITY_THRESHOLD = 1;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

     /*   @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Log.w("onSingleTapConf","tap");
            return true;
        }*/

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }
}

Open MainActivity.java file and add below code.


MainActivity.java

									   
package com.narendra.gallery;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    ImageView selectedimage;
    CarveGallery gallery;
    Context context;
    Integer[] pics = {
            R.drawable.fan,
            R.drawable.youtube,
            R.drawable.icon_twitter,
            R.drawable.instagram,
            R.drawable.offers_icon,
            R.drawable.twiiterr,
            R.drawable.youtube,
            R.drawable.instagram,
            R.drawable.offers_icon,
            R.drawable.instagram,
            R.drawable.fan
    };
    private int deviceHeight;
    private int deviceWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=this;
        getScreenSize();
        findID();

		 selectedimage.setOnTouchListener(new OnSwipeTouchListener(context) {

            @Override
            public void onSwipeRight() {
                gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
            }

            @Override
            public void onSwipeLeft() {
                gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
            }
        });
		
        gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                selectedimage.setImageResource(pics[position]);
                view.setPadding(0, 0, 0, 10);
            }

            @Override
            public void onNothingSelected(AdapterView parent) {

            }
        });


        gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView arg0, View arg1, int arg2,
                                    long arg3) {
                Toast.makeText(getBaseContext(),
                        "Picture " + (arg2 + 1), Toast.LENGTH_SHORT).show();
                selectedimage.setImageResource(pics[arg2]);

            }

        });
    }

    private void findID() {

        gallery = (CarveGallery) findViewById(R.id.galleryshow);
        selectedimage = (ImageView) findViewById(R.id.imageshow);
        gallery.setAdapter(new ImageAdapter(this));
    }

    public void getScreenSize() {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        deviceHeight = metrics.heightPixels;
        deviceWidth = metrics.widthPixels;

    }

    public class ImageAdapter extends BaseAdapter {

        int imageBackground;
        private Context ctx;

        public ImageAdapter(Context c) {
            ctx = c;
            TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
            ta.recycle();
        }

        @Override
        public int getCount() {

            return pics.length;
        }

        @Override
        public Object getItem(int arg0) {

            return arg0;
        }

        @Override
        public long getItemId(int arg0) {

            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            ImageView iv = new ImageView(ctx);
            iv.setImageResource(pics[arg0]);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new Gallery.LayoutParams(deviceWidth * 25 / 100, deviceHeight * 15 / 100));
            return iv;
        }
    }
}

Tags

  • Android

  • Android Studio

  • Android development

  • Java