Thursday, July 25, 2013

Android Gallery View Example

A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.

  • 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.


Android GalleryView




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

Android GalleryView



 

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.






30 comments:

  1. hello, great tutorial but please if you can tell us how to set the image as wallpaper
    EX: if the five is showed than I can set 5 as wallpaper

    ReplyDelete
  2. 1.in xml take one button
    2.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();
    }
    }

    ReplyDelete
  3. hi..

    I 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..

    ReplyDelete
  4. Hello,
    how to use this for load image from internet gallery?

    thanks for tutorial.

    ReplyDelete
  5. Hey :) 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 :)

    ReplyDelete
  6. Hi.. Its a very nice tutorial. However, I have one requirement.
    I 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

    ReplyDelete
  7. i got error on this code Gallery gallery = (Gallery) findViewById(R.id.gallery1);
    it's say cant cast from view to gallery

    can you help me?

    ReplyDelete
  8. Thanx a lot....very usefull for me..

    ReplyDelete
  9. Thanx a lot....very helpfull for me..

    ReplyDelete
  10. Excellent code...for displaying images as well as for selling wallpaper...thankx a lotttt....:)

    ReplyDelete
  11. what about if I'd wanted to use an intent on click of one of those numbers,how can I achieve that?

    ReplyDelete
  12. hi i want to send the image which user selects...........thanks in advance

    ReplyDelete
  13. Thank you, this post worked for me

    ReplyDelete
  14. Anyone has a project file? Can't get this to work :/

    ReplyDelete
  15. Just for info. Need to add the following permissions in manifest to set the wallpaper

    ReplyDelete
  16. Thank you for the code it is very useful.
    just for info: Need to set the following permissions in manifest to set the wallpaper

    ReplyDelete
  17. Thanks for the tutorial. It was really useful!

    ReplyDelete
  18. Should we write something in manifest ? thank you

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. How can i define a Title in the array and pass the value to the onClick event to show in a TextView?

    ReplyDelete
  21. Thanks in support of sharing such a pleasant opinion,
    paragraph is fastidious, tjats why i have rread it completely

    ReplyDelete
  22. 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

    ReplyDelete
    Replies
    1. Thnaks for your appreciation.
      You can download an app https://play.google.com/store/apps/details?id=com.useful.gps

      Delete