Tarea relativamente simple: ¿Cómo devuelvo el elemento seleccionado de una actividad a otra?

I have two activities: one displays an image and a button, the other displays a photo gallery. I want to be able to select any of the images in the gallery and then display them on the first activity in place of the default image.

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) {
            Toast.makeText(PhotoGallery.this, "Position: " + id, Toast.LENGTH_SHORT).show();

            Intent intent=new Intent();   
            intent.putExtra("PictureID", position);
            setResult(RESULT_OK, intent);
            finish();


        }
    });
}

Am I even close here? I'm not quite sure what to do with any string or int I would attach to the Intent -- can I attach the object itself? I'd much rather pass back at minimum the string name of the resource (image), but the only thing I can seem to figure out right now is how to pass back the position of the picture ... not a great solution. I can clarify more if necessary -- thanks.

EDIT:

For anyone who comes across this in the future, here's the result of my app. Simple, but works! http://www.youtube.com/watch?v=WJjEvwy8yDc

preguntado el 09 de enero de 11 a las 06:01

Are you calling the second activity with startActivityForResult, not just startActivity ? For putting objects into the intent, they need to be parcelable (developer.android.com/reference/android/os/Parcelable.html), but I'd prefer to just pass the image index/position or resource id. -

Yes, I did call it with the startActivityForResult. I would prefer to pass the resourceid .. how do I access that? (This is my very first android app, thus the massive noobery :]) -

1 Respuestas

As you are new to Android you should take a look at the Android samples provided with the SDk. What you want to do can be achieved by an ImageSwitcher. You can take a look at the ImageSwitcher example in the Android ApiDemos sample.

Sample from Android samples :

ImageSwitcher1.java

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;


public class ImageSwitcher1 extends Activity implements
        AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.image_switcher_1);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        mSwitcher.setImageResource(mImageIds[position]);
    }

    public void onNothingSelected(AdapterView parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        return i;
    }

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.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(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }

        private Context mContext;

    }

    private Integer[] mThumbIds = {
            R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
            R.drawable.sample_thumb_2, R.drawable.sample_thumb_3,
            R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
            R.drawable.sample_thumb_6, R.drawable.sample_thumb_7};

    private Integer[] mImageIds = {
            R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
            R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7};

}

image_switcher_1.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ImageSwitcher android:id="@+id/switcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
    />

    <Gallery android:id="@+id/gallery"
        android:background="#55000000"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"

        android:gravity="center_vertical"
        android:spacing="16dp"
    />

</RelativeLayout>

Respondido el 09 de enero de 11 a las 09:01

Thanks, I will give that a thorough read -- just to follow up, I was able to solve my problem by simply passing back the position, and then creating the same array in the initial Activity. Then I just treat the position as an index and replace that image with the image at the index returned. - Brian D

That will also work but I just wanted to point you to a more standard way of doing what you wanted to do. - Deepak Singh Rawat

I understand -- I'm looking through it now. I think it'd be a better solution, since I'm now finding that when my phone rotates, I think it's calling the OnCreate and replacing whatever the selected image was with the original default image :) - Brian D

So, turns out this is exactly what I want to do -- only, the purpose of the assignment is to practice passing intents between activities. So, while this essentially has the same function to the user, I've still got to use two activities. Very helpful though, so I'll give it to you. - Brian D

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.