[英]Extract info sent between two Activities in adapter for Android app
我的第一个活动在网格中显示图像,并在每个图像上实现onclick方法,它将发送信息并在单击时打开第二个活动。
我想构造一个图像适配器以在第二个活动中处理该图像。 如何提取图像适配器内部单击的图像的图像ID,以告诉适配器我希望其与在第一个活动中单击的图像一起使用?
启动FullSize
活动的代码:
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
Intent puzzle = new Intent(this, FullSize.class);
puzzle.putExtra("selected_img", id);
startActivity(puzzle);
}
您可以将图像ID传递给自定义适配器的构造函数。
首先,请确保您正在发送图像资源ID。 目前看来,您正在额外发送行ID。 当您调用puzzle.putExtra("selected_img", id);
, id
实际上是AdapterView
的行ID。 在这里查看文档
您实际上需要传递的是imageList.get(position)
以获得当前所选项目的图像资源ID。
一旦工作,您可以执行以下操作:
传递您的图片ID:
Intent i = getIntent();
int imageID = i.getIntExtra("selected_img", 0);
ImageAdapter ia = new ImageAdapter(this, imageID);
定制适配器,其中图像ID作为构造函数中的参数:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
int imageID;
public ImageAdapter(Context c, int imageResourceID) {
mContext = c;
imageID = imageResourceID;
}
public int getCount() {
return 1;
}
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(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageID); //use the image id passed in through the constructor
return imageView;
}
}
您可以使用Extras在活动之间传递数据
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putExtra("imgId", id);
startActivity(intent);
然后在第二个活动中将其取回:
Intent intent = getIntent();
int imgId = intent.getIntExtra("imgId");
您如何处理ID由您决定。
如前面的答案中所述,您可以使用putExtra
或者,您可以使用setData
。 如果您要处理应用资源以外的图像,则必须处理Uri
。 在这种情况下,请使用
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.setData(uri);
startActivity(intent);
在第二项活动中,您可以使用
Intent intent = getIntent();
Uri uri = intent.getData ();
Uri
对象可用于读取图像文件或有关图像的元数据。 Uri也可以是远程文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.