Post Top Ad

Post Top Ad

Saturday 11 February 2017

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)

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. 
 

Handle touch/click event on Gallery:
We need to add click Listener to gallery  in order to handle the touch event on gallery.

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :


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


ImageSwitcher Example:

 

In the above layout, we  have an ImageSwitcher and a button called "NEXT" , when user clicks on NEXT button   ImageSwitcher will switch between Images . The current Image will go OUT and next Image will come in with specified Animation.



example1_layout.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  
   <ImageSwitcher 
            android:id="@+id/imageSwitcher"
            android:layout_marginTop="50dp"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_gravity="center_horizontal" />
   
  
      <Button 
            android:id="@+id/buttonNext"
            android:layout_marginTop="150dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:text="NEXT"
           />
    

</LinearLayout>




ImageSwitcherExampleActivity.java


public class ImageSwitcherExample1Activity extends Activity
{

            private ImageSwitcher imageSwitcher;
            Button btnNext;
            
            
           
 // Array of Image IDs to Show In ImageSwitcher 
            int imageIds[]={R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5,R.drawable.image6,};
            int messageCount=imageIds.length;
           
 // to keep current Index of ImageID array
            int currentIndex=-1; 

            

            @Override
            protected void onCreate(Bundle savedInstanceState) 
            {
                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.
example_layout);
                        
                   
     // get The references 
                        btnNext=(Button)findViewById(R.id.buttonNext);
                        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
                        
                    
    // Set the ViewFactory of the ImageSwitcher that will create ImageView object when asked
                        imageSwitcher.setFactory(new ViewFactory() {
                            
                            public View makeView() {
                                // TODO Auto-generated method stub
                                
                                    /
/ Create a new ImageView set it's properties 
                                    ImageView imageView = new ImageView(getApplicationContext());
                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                    imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
                                    return imageView;
                            }
                        });

                     
   // Declare the animations and initialize them
                        Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
                        Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);
                        
                       
 // set the animation type to imageSwitcher
                        imageSwitcher.setInAnimation(in);
                        imageSwitcher.setOutAnimation(out);
                    

                       
 // ClickListener for NEXT button
                        // When clicked on Button ImageSwitcher will switch between Images 
                        // The current Image will go OUT and next Image  will come in with specified animation

                        btnNext.setOnClickListener(new View.OnClickListener() {
                            
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                 currentIndex++;
                                 
  // If index reaches maximum reset it
                                    if(currentIndex==messageCount)
                                        currentIndex=0;
                                    imageSwitcher.setImageResource(imageIds[currentIndex]);
                            }
                        });
                        
            }
            
}
    

Image Switcher is similar to imageView but image switcher is a element of Transition Widget. so, here we display image with some animated style. In image switcher image view create at run time and if i want then we also add some animation.

Code  Discription:-


java source code:- 




import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.widget.Button;

import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class ImageSwitcherExampleActivity extends Activity implements ViewFactory{
ImageSwitcher is;
int [] imgid = {R.drawable.shivendra,R.drawable.krishna,R.drawable.madina,R.drawable.sai,R.drawable.sambhu,R.drawable.tirupati};
Button prev, next;
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_switcher_example);

is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
prev = (Button)findViewById(R.id.button1);
next = (Button)findViewById(R.id.button2);
is.setFactory(this);
is.setInAnimation(this, android.R.anim . slide_in_left);
is.setOutAnimation(this, android.R.anim.slide_out_right);

prev.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count>0)
{
count--;
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(ImageSwitcherExampleActivity.this, "First Image Reached", Toast.LENGTH_LONG).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count
{


try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
count++;

}
else
{
Toast.makeText(ImageSwitcherExampleActivity.this, "last Image Reached", Toast.LENGTH_LONG).show();
}
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.image_switcher_example, menu);
return true;
}

@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

return iv;
}

}

Layout xml code:-


xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ImageSwitcherExampleActivity" >


android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >


android:id="@+id/imageSwitcher1"
android:layout_width="match_parent"
android:layout_height="match_parent" >




android:layout_width="match_parent"
android:layout_height="wrap_content" >
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="<<" />
 
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=">>" />



Image Switcher View | Android Developer Tutorial

Now we will explore ImageSwitcher View. It is a view useful to switch smoothly between two images and thus provides ways of transitioning from one to another through appropriate animations.

We will implement the same concept of showing a gallery of images that scrolls at the top of the android screen landscape and upon selection of one image, it gets displayed as a larger image in the lower part through the use of an ImageSwitcher. This is what I had done earlier in the GalleryView tutorial but now instead of showing the selected picture through an ImageView, I will show it using a ImageSwitcher. Though the output may seem very similar, lot of other methods are available on the ImageSwitcher that can be used, if required.

 

   

No comments:

Post a Comment