如何从图库窗口小部件中选择图像并在另一个活动中显示?

时间:2013-03-05 23:13:23

标签: android image android-activity gallery selected

我正在尝试从Gallery Widget加载选定的图像并将其加载到另一个活动中,我将非常感谢您的帮助!

基本上它是关于我在图库中选择的图像,并在OnItemClick中创建一个意图,或者我不知道在另一个活动中查看图像。

班级看起来像这样:

public class Motos extends Activity implements OnClickListener, OnItemSelectedListener, OnItemClickListener{

    Gallery g;

Integer[] images = {
        R.drawable.image1,
        R.drawable.image2,
        R.drawable.image3,
        R.drawable.image4 };


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.moto);


    g = (Gallery) findViewById(R.id.gallery1);
    g.setOnItemClickListener(this);
    g.setSpacing(2);


}

public class ImageAdapter extends BaseAdapter {

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return images.length;
    }

    public Object getItem(int position) {
        return images[position];
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView i = new ImageView(mContext);

        i.setImageResource(images[position]);
        i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        //i.setLayoutParams(new Gallery.LayoutParams(136, 88));
        return i;
    }

    private Context mContext;

}


@Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
    // TODO Auto-generated method stub

}

}

1 个答案:

答案 0 :(得分:0)

好吧,看起来您可以通过执行以下操作获取所选图像的资源ID:

@Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
    int selectedId = images[position];  
}

您可以将选定的资源ID传递给另一个Activity,如下所示:

Intent intent = new Intent(Vehiculos.this, OtherActivity.class);
intent.putExtra("imageId", selectedId);
startActivity(intent);

然后在您的其他Activity中检索ID,如下所示:

Intent intent = getIntent();
int imageId = intent.getIntExtra("imageId", -1); // -1 would be a default value

这是一个粗略的例子 - 您可能需要添加一些错误检查。