开发者

How to create a Photo Gallery on Android?

I want to create a photo gallery on Android. I'm using Gallery and BaseAdapter to create a scrollable gallery. Now I want to add an action when an image of the gallery is shown (each image's width is the same as screen width), so I need to get its index in the image array. My question is how to get the index of the image which shows on the screen?

I want to get the index of the image as soon as it shows on the screen, not on click event. I've tried to get current image position in getView(), but the result is strange:

I scroll to image02 but position=2 (should be 1). When I scroll back, image02's position=0 (should be 1).

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       

        Gallery g = (Gallery) this.findViewById(R.id.Gallery);  
        g.setAdapter(new ImageAdapter(this));
}

public class ImageAdapter extends BaseAdapter {  

    private Context mContext;  
    private Integer[] mImageIds = {  
            //each image's size is 320x60
            R.drawable.btm01,  
            R.drawable.btm02,  
            R.drawable.btm03
    };  
    public ImageAdapter(Context c){  
        this.mContext = c;  
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mImageIds.length;
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public long getItemId(int position) {开发者_如何学C
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ImageView imageView = new ImageView(mContext);  
        imageView.setImageResource(mImageIds[position]);  
        imageView.setLayoutParams(new Gallery.LayoutParams(320,60));    
        return imageView;  
    }


Check this example.

// Reference the Gallery view
Gallery g = (Gallery) this.findViewById(R.id.Gallery);  
// Set the adapter to our custom adapter (below)
g.setAdapter(new ImageAdapter(this));

// Set a item click listener, and just Toast the clicked position
g.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView parent, View v, int position, long id) {
    Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜