Wednesday, February 27, 2013

Gallery View in Android

Here we learn how to create gallery view in android application.


For Create gallery View in android we need create one Image Adapter class for display image in fullscreen in gallery view.

For create Gallery view Activity looks like this.
public class MainActivity extends Activity implements OnItemClickListener
{
private static final String tag = "Main";
private Gallery _gallery;
private ImageAdapter _imageAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

_gallery = (Gallery) this.findViewById(R.id.gallery1);
_imageAdapter = new ImageAdapter(this);
_gallery.setAdapter(_imageAdapter);
_gallery.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView arg0, View view, int position, long duration)
{
int resourcId = (Integer) _imageAdapter.getItem(position);
Drawable drawable = getResources().getDrawable(resourcId);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourcId);

Toast.makeText(this, "Selected Image: " + getResources().getText(resourcId) + "\nHeight: " + bitmap.getHeight() + "\nWidth: " + bitmap.getWidth(), Toast.LENGTH_SHORT).show();
}
}

Xml File for this activity looks like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>

<Gallery
android:id="@+id/gallery1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:spacing="10dip"
>
</Gallery>
</LinearLayout>


Image Adapter class

public class ImageAdapter extends BaseAdapter {
private Context _context = null;
private final int[] imageIds = { R.drawable.ic_launcher
, R.drawable.ic_launcher
, R.drawable.ic_launcher, R.drawable.ic_launcher, 
R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher };

public ImageAdapter(Context context) {
this._context = context;

}

@Override
public int getCount() {
return imageIds.length;
}

@Override
public Object getItem(int index) {
return imageIds[index];
}

@Override
public long getItemId(int index) {
return index;
}

@Override
public View getView(int postion, View view, ViewGroup group) {
ImageView imageView = new ImageView(_context);

imageView.setImageResource(imageIds[postion]);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return imageView;
}
}





No comments:

Post a Comment