Gallery View in android studio.

Android 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 file 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/image_show"
        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">

        <Gallery
            android:id="@+id/gallery_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_gravity="center"
            android:layout_weight=".4"
            android:spacing="3dp" />
    </RelativeLayout>
</LinearLayout>

	

Now create a new xml file in values


attributes.xml

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

Now create a new java file and Add below Code.


OnSwipeTouchListener.java

									   
package com.narendra.gallerysimple;

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;
        }
    }
}

Now open MainActivity.java class and add code.


MainActivity.java

									   
package com.narendra.gallerysimple;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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;
    Gallery 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 = (Gallery) findViewById(R.id.gallery_show);
        selectedimage = (ImageView) findViewById(R.id.image_show);
        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