所以我有一个程序Gallery
(用资源文件夹中的图片制作),一个按钮和一个ImageView
我想从图库中选择一个图像,按下按钮,然后更改ImageView
位图以显示从图库中选择的图像...
我有从活动到活动的不断变化的方法都已修复...但我只是难以获得所选图像的 id ,整数,< strong> drawable ,long,string ......或者它有什么帮助...
以下是代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
//CODE TO KNOW IF PICKED THE 1ST OR 2ND IMAGE
//Toast.makeText(Galeria.this, v.getId() + "", Toast.LENGTH_SHORT).show();
//Toast.makeText(Galeria.this, parent.getItemIdAtPosition(position) + "", Toast.LENGTH_SHORT).show();
//Toast.makeText(Galeria.this, id + "", Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageId = {
R.drawable.image1, //first image
R.drawable.image2, //second image
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = c.obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount()
return mImageId.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageId[position]);
i.setLayoutParams(new Gallery.LayoutParams(400, 225));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
OnItemClick
虚空中的三个Toast是我尝试显示id ...但只显示图库中图像的位置。
还有其他解决方案吗?我已经读过关于动力学的东西......但是可以理解......
我应该把代码放在哪里以获得我想要的ID?
任何帮助?感谢。
答案 0 :(得分:1)
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
//CODE TO KNOW IF PICKED THE 1ST OR 2ND IMAGE
int imageId = (Integer) (parent.getItemAtPosition(position));
myImageView.setImageResource(imageId);
//Toast.makeText(Galeria.this, v.getId() + "", Toast.LENGTH_SHORT).show();
//Toast.makeText(Galeria.this, parent.getItemIdAtPosition(position) + "", Toast.LENGTH_SHORT).show();
//Toast.makeText(Galeria.this, id + "", Toast.LENGTH_SHORT).show();
}
});
在你的适配器中,getItem应该返回数据集的对象
public Object getItem(int position) {
return (mImageId[position]);
}
答案 1 :(得分:0)
您可以执行以下操作,将image view
resource
drawable
作为itemClickListener
:
(ImageView)view.getBackground()
这将返回图像作为所选图像视图资源的可绘制对象。