1

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

我想在屏幕上显示图像时立即获取图像的索引,而不是点击事件。我试图在 中获取当前图像位置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;  
    }
4

1 回答 1

2

检查这个例子。

// 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();
  }
});
于 2010-11-16T11:47:36.347 回答