如何在Android上创建照片库?

时间:2010-11-16 10:55:43

标签: android image-gallery

我想在Android上创建照片库。我正在使用GalleryBaseAdapter来创建可滚动的图库。现在我想在显示图库的图像时添加一个动作(每个图像的宽度与屏幕宽度相同),所以我需要在图像数组中获取它的索引。我的问题是如何获取屏幕上显示的图像索引

我想在屏幕上显示图像的索引,而不是点击事件。 我试图在getView()中获取当前图像位置,但结果很奇怪:

我滚动到image02但位置= 2(应该是1)。当我向后滚动时,image02的位置= 0(应为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) {
        // 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;  
    }

1 个答案:

答案 0 :(得分:2)

检查this示例。

// 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();
  }
});