我正在尝试创建一个图库,当您点按缩略图时,该图库将全屏显示图片。
我遵循了一个很好地创建了图库的教程,但我不知道如何为每个图像缩略图提供onClick事件。
在我的图库页面中,在onCreate中,我有这个:
public class GalleryPage extends Activity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_page);
...
this.imageGrid = (GridView) findViewById(R.id.gallery_container);
this.bitmapList = new ArrayList<Bitmap>();
File f = new File(latest_directory);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++) {
this.bitmapList.add(loadImage(latest_directory + "/" + file[i].getName()));
}
this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));
}
}
然后,ImageAdapter看起来像这样:
public class ImageAdapter extends BaseAdapter {
private Context context;
private ArrayList<Bitmap> bitmapList;
public ImageAdapter(Context context, ArrayList<Bitmap> bitmapList) {
this.context = context;
this.bitmapList = bitmapList;
}
public int getCount() {
return this.bitmapList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(this.context);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(this.bitmapList.get(position));
return imageView;
}
}
我以为我可以这样做:
imageView.setOnClickListener("onImageClick");
并在我的图库页面中有一个方法,但这会引发错误。
当我点击任何动态创建的图库图像(imageView
)时,我怎么能这样做,我可以获取图像位置来拉动图像并将其放置在全尺寸叠加中。
答案 0 :(得分:1)
将OnItemClickListener
设置为GridView
。
imageGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
//Selected bitmap
Bitmap bitMap = bitmapList.get(position);
//Do something with it
}
});
答案 1 :(得分:1)
使用setOnItemClickListener
。
如果您想使用自定义界面,请按照:
创建界面
public interface ItemClickListener {
void onItemClick(Bitmap t, int position);
}
在适配器集Listener:
中public class ImageAdapter extends BaseAdapter {
/// your code
private ItemClickListener listener;
public void setListener(ItemClickListener listener) {
this.listener = listener;
}
// your code
}
在getView方法中
public View getView(int position, View convertView, ViewGroup parent) {
// your code
Bitmap bitmap = this.bitmapList.get(position);
imageView.setImageBitmap(bitmap );
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(bitmap,position);
}
});
return imageView;
}
那就是它。现在在您的Activity中实现它。