A Gallery is a View commonly used to display items in a horizontally
scrolling list that locks the current selection at the center.
In our GalleryView Example we have populated the Gallery with images.
The images will be shown in horizontal list, when user selects/click on an image , the selected Image will be shown in center of the screen. (See the Screenshot below)
Handle touch/click event on Gallery:
We need to add click Listener to gallery in order to handle the touch event on gallery.
We have a gallery and an ImageView, we will show the User selected image in ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Gallery
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView1"
android:layout_marginTop="100dp"
android:layout_width="250dp"
android:layout_gravity="center_horizontal"
android:layout_height="250dp"
android:src="@drawable/image1" />
</LinearLayout>
public class MainActivity extends Activity
{
ImageView selectedImage;
private Integer[] mImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
selectedImage=(ImageView)findViewById(R.id.imageView1);
gallery.setSpacing(1);
gallery.setAdapter(new GalleryImageAdapter(this));
// clicklistener for Gallery
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();
// show the selected Image
selectedImage.setImageResource(mImageIds[position]);
}
});
}
}
public class GalleryImageAdapter extends BaseAdapter
{
private Context mContext;
private Integer[] mImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
public GalleryImageAdapter(Context context)
{
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Override this method according to your need
public View getView(int index, View view, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[index]);
i.setLayoutParams(new Gallery.LayoutParams(200, 200));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}
- Gallery can be used to show Views in a horizontal list, and user can select a View , User selected view will be shown in center of the Horizontal list
- The items of Gallery are populated from an Adapter, similar to ListView, in which ListView items are populated from an Adapter.
- We need to create an Adapter class which extends BaseAdapter class and override getView() method.
- getView() method called automatically for all items of Gallery (similar to list view in which getView() method called for each item of ListView)
GalleryView Example
In our GalleryView Example we have populated the Gallery with images.
The images will be shown in horizontal list, when user selects/click on an image , the selected Image will be shown in center of the screen. (See the Screenshot below)
Handle touch/click event on Gallery:
We need to add click Listener to gallery in order to handle the touch event on gallery.
main.xml
We have a gallery and an ImageView, we will show the User selected image in ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Gallery
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView1"
android:layout_marginTop="100dp"
android:layout_width="250dp"
android:layout_gravity="center_horizontal"
android:layout_height="250dp"
android:src="@drawable/image1" />
</LinearLayout>
MainActivity
public class MainActivity extends Activity
{
ImageView selectedImage;
private Integer[] mImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
selectedImage=(ImageView)findViewById(R.id.imageView1);
gallery.setSpacing(1);
gallery.setAdapter(new GalleryImageAdapter(this));
// clicklistener for Gallery
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();
// show the selected Image
selectedImage.setImageResource(mImageIds[position]);
}
});
}
}
GalleryImageAdapter
public class GalleryImageAdapter extends BaseAdapter
{
private Context mContext;
private Integer[] mImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
public GalleryImageAdapter(Context context)
{
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Override this method according to your need
public View getView(int index, View view, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[index]);
i.setLayoutParams(new Gallery.LayoutParams(200, 200));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}
New Advance Topics: Android LiveWallpaer Tutorial
Android ImageSwitcher Android TextSwitcher Android ViewFlipper
Android Gesture Detector Handling/Detecting Swipe Events Gradient Drawable
Detecting Missed Calls Hide Title Bar GridView Animation
Android AlarmManager Android BootReceiver Vibrate Phone In a Desirable Pattern
Developing for Different Screen Sizes Showing Toast for Longer Time Publishing your App
How to publish Android App on Google Play
Android TextWatcher Android ExpandableListView
Beginning With Android
Android : Introduction(What is Android) Configuring Eclipse for Android Development
Creating Your First Android Project Understanding Android Manifest File of your android app
Advance Android Topics Customizing Android Views
Working With Layouts Working With Views
Understanding Layouts in Android Using Buttons and EditText in Android
Working with Linear Layout (With Example) Using CheckBoxes in Android
Nested Linear Layout (With Example) Using AutoCompleteTextView in Android Grid View
Relative Layout In Android ListView
Table Layout Android ProgressBar
Frame Layout(With Example) Customizing ProgressBar
Absolute Layout Customizing Radio Buttons
Grid Layout Customizing Checkboxes In Android
Android Advance Views
Android Spinner Android GalleryView
Android TabWidget Android ExpandableListView
Android Components Dialogs In Android
Activity In Android Working With Alert Dialog
Activity Life Cycle Adding Radio Buttons In Dialog
Starting Activity For Result Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android Creating Customized Dialogs in Android
Returning Result from Activity Creating Dialog To Collect User Input
Android : Service DatePicker and TimePickerDialog
BroadcastReceiver Using TimePickerDialog and DatePickerDialog In android
Menus In Android ListView:
Creating Option Menu Populating ListView With DataBase
Creating Context Menu In Android Populating ListView with ArrayList
ListView with Custom Adapter
Toast Working With SMS
Customizing Toast In Android How to Send SMS in Android
Customizing the Display Time of Toast How To Receive SMS
Customizing Toast At Runtime Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time
TelephonyManager Storage: Storing Data In Android
Using Telephony Manager In Android SharedPreferences In Android
Reading and Writing files to Internal Stoarage
Working With Incoming Calls DataBase : Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android Working With Database in Android
How to Forward an Incoming Call In Android Creating Table In Android
CALL States In Android Inserting, Deleting and Updating Records In Table in Android
Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.
hello, great tutorial but please if you can tell us how to set the image as wallpaper
ReplyDeleteEX: if the five is showed than I can set 5 as wallpaper
1.in xml take one button
ReplyDelete2.find in java file
btn_wallpaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setAsWallpaper(v);
}
});
3.one more methos for set wallpaper
--->selectedImage---ur image view
public void setAsWallpaper(View v) {
selectedImage.buildDrawingCache();
Bitmap mBitmap = selectedImage.getDrawingCache();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1;
int width1=width/2;
mBitmap = Bitmap.createScaledBitmap(mBitmap,width1, height, true);
try {
myWallpaperManager.setBitmap(mBitmap);
myWallpaperManager.suggestDesiredDimensions(width1, height);
Toast.makeText(GalleryActivity.this, "Wallpaper set",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(GalleryActivity.this, "Error setting wallpaper",
Toast.LENGTH_SHORT).show();
}
}
hi..
ReplyDeleteI need same but instade of image list , i have to display list of books. and on selection book name needs to open new activity with that name to be forward in intent.
How to do it ?
Basically a horizontal list..
Hello,
ReplyDeletehow to use this for load image from internet gallery?
thanks for tutorial.
Thanks, this really helps.
ReplyDeleteThanks, this really helps.
ReplyDeleteHey :) thanks for the code it worked a treat. Just wondering if there would be any way to add sound? So when I click an image it would play a sound. Could this be done through buttons? thanks a million for any response :)
ReplyDeleteHi.. Its a very nice tutorial. However, I have one requirement.
ReplyDeleteI see that in current example, the gallery appears on top of screen from left to right while in Landscape mode. I want the gallery to appear from top to bottom on the right end of the screen and selected item will be displayed in the middle. How to achieve it?
Thanks and Regards
i got error on this code Gallery gallery = (Gallery) findViewById(R.id.gallery1);
ReplyDeleteit's say cant cast from view to gallery
can you help me?
Thanks alot
ReplyDeleteThanx a lot....very usefull for me..
ReplyDeleteThanx a lot....very helpfull for me..
ReplyDeleteExcellent code...for displaying images as well as for selling wallpaper...thankx a lotttt....:)
ReplyDeletewhat about if I'd wanted to use an intent on click of one of those numbers,how can I achieve that?
ReplyDeletehi i want to send the image which user selects...........thanks in advance
ReplyDeleteThank you, this post worked for me
ReplyDeleteImageAdapter Eror help me
ReplyDeleteWhat is the error ?
DeleteAnyone has a project file? Can't get this to work :/
ReplyDeleteJust for info. Need to add the following permissions in manifest to set the wallpaper
ReplyDeleteThank you for the code it is very useful.
ReplyDeletejust for info: Need to set the following permissions in manifest to set the wallpaper
Thanks for the tutorial. It was really useful!
ReplyDeleteoh. nice tut :)
ReplyDeleteThanks!!
ReplyDeleteShould we write something in manifest ? thank you
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHow can i define a Title in the array and pass the value to the onClick event to show in a TextView?
ReplyDeleteThanks in support of sharing such a pleasant opinion,
ReplyDeleteparagraph is fastidious, tjats why i have rread it completely
I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information. love it
ReplyDeleteThnaks for your appreciation.
DeleteYou can download an app https://play.google.com/store/apps/details?id=com.useful.gps