Gallery Example
Gallery is a view used to show items in a center locked, horizontal scrolling list and user will select a view and then user selected view will be shown in the center of the Horizontal list. The items in Gallery are added using adapter just like in ListView or GridView.
actvity_main.xml
This xml shows imageview and gallery which is in listview shape.
MainActivity.java
This activity shows images array and use adapter to fill the images in gallery listview.
package com.example.icowboysradio.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Gallery; import android.widget.ImageView; public class MainActivityGallery extends AppCompatActivity{ Gallery gallery; CustomGalleryAdapter customGalleryAdapter; ImageView imageView; int[] images = {R.mipmap.ic_launcher, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); gallery = (Gallery) findViewById(R.id.gallery); imageView = (ImageView) findViewById(R.id.imageView); customGalleryAdapter = new CustomGalleryAdapter(getApplicationContext(), images); gallery.setAdapter(customGalleryAdapter); gallery.setSpacing(10); gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { imageView.setImageResource(images[position]); } }); } }
CustomAdapter.java
This Adapter use to add images into gallery listview
package com.example.icowboysradio.myapplication; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; public class CustomGalleryAdapter extends BaseAdapter { private Context context; private int[] images; public CustomGalleryAdapter(Context act, int[] images) { context = act; this.images = images; } public int getCount() { return images.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(context); imageView.setImageResource(images[position]); imageView.setLayoutParams(new Gallery.LayoutParams(200, 200)); return imageView; } }
Leave A Comment