Use PagerAdapter to display Image

Description

The following code shows how to Use PagerAdapter to display Image.

Example


import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
//from  ww  w .  j a  v a 2s.  c o m
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewPager pager = new ViewPager(this);
        pager.setAdapter(new ImagePagerAdapter(this));
        
        setContentView(pager);
    }
}

class ImagePagerAdapter extends PagerAdapter {
    private Context mContext;
    
    private static final int[] IMAGES = {
        android.R.drawable.ic_menu_camera,
        android.R.drawable.ic_menu_add,
        android.R.drawable.ic_menu_delete,
        android.R.drawable.ic_menu_share,
        android.R.drawable.ic_menu_edit
    };
    
    private static final int[] COLORS = {
        Color.RED,
        Color.BLUE,
        Color.GREEN,
        Color.GRAY,
        Color.MAGENTA
    };
    
    public ImagePagerAdapter(Context context) {
        super();
        mContext = context;
    }
    @Override
    public int getCount() {
        return 5;
    }
    @Override
    public float getPageWidth(int position) {
        return 0.333f;
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView iv = new ImageView(mContext);

        iv.setImageResource(IMAGES[position]);
        iv.setBackgroundColor(COLORS[position]);

        container.addView(iv);
        return iv;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
    
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }
    
}




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView