How to take a selected image from gallery widget a

2019-09-09 02:20发布

问题:

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.