How to take a selected image from gallery widget and show in another activity?

余生长醉 提交于 2019-12-24 20:12:14

问题


I am trying to load a selected image from Gallery Widget and load it in another activity, I will really appreciate help!

Basically it is about take the image that I select in the Gallery and make in the OnItemClick an Intent or I don`t know to view the image in another Activity.

The class look like this:

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:


Well, looks like you can get the resource ID of the selected image by doing the following:

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

You could pass that selected resource id to another Activity like this:

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

And then retrieve the id in your other Activity like this:

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

This is a rough example - you will probably need to add some error-checking.



来源:https://stackoverflow.com/questions/15235967/how-to-take-a-selected-image-from-gallery-widget-and-show-in-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!