在Android中如何将图像设置为不同活动的imageView?

时间:2015-01-13 02:52:54

标签: java android android-activity onclick imageview

我想将imageView的背景更改为我在另一个类的库中的图像。到目前为止,我有一个带有imageView的Main活动,它通过defualt显示其中一张图片,我想从我在另一个活动OnClick上创建的图库中将该图像更改为另一个图像。

谢谢,

这里有两项活动:

main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/welcome"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageSelected"
    android:background="@drawable/brien"
    android:layout_above="@+id/ButtonChangePic"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/changePic"
    android:id="@+id/ButtonChangePic"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="146dp"
    android:onClick="changePicture"/>

Main.java

package com.gallery.brien.picturegallery;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Picture;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class Main extends Activity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void changePicture(View view) {
    // Open picture gallery activity
    Intent intent = new Intent(this,PictureGallery.class);
    startActivity(intent);

}

}

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;


public class PictureGallery extends Activity {

//variable array where pictures are store
Integer[] Profile = {R.drawable.brien, R.drawable.kick, R.drawable.mma, R.drawable.fun,
        R.drawable.run};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.picture_gallery);

    //  UI of gallery display. Initializes the GridView and ItemView
    //  classes. Then wait for interaction from user.
    GridView gal = (GridView) findViewById(R.id.gridView);
    final ImageView imageView = (ImageView) findViewById(R.id.imageSelected);

    //  Calls the ImageAdapter Class.
    gal.setAdapter(new ImageAdapter(this));
    // Calls the onItemClickListener Class
    gal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override

       /*                onItemClick Method
       The onItemClick method has four arguments.
        AdapterView<?> arg0 - Records where the user touched screen
        View arg1 - Parameters of the View user touched
        int arg2  - Integer value that holds the position of the View
                    in the adapter.
        long arg3 - Determines the row id of the item that was
                     selected by the user.
        */
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            Toast.makeText(getBaseContext(), "You have selected picture " + (arg2)
                    + " Brien Calloway", Toast.LENGTH_SHORT).show();
            imageView.setImageResource(Profile[arg2]);



        }
    });


}

public class ImageAdapter extends BaseAdapter{

    private Context context;
    public ImageAdapter(Context c){
        context=c;
    }

    @Override
    public int getCount() {return Profile.length;}

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        ImageView pic = new ImageView(context);
        pic.setImageResource(Profile[arg0]);
        pic.setScaleType(ImageView.ScaleType.FIT_XY);
        pic.setLayoutParams(new GridView.LayoutParams(200,175));
        return pic;

    }
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_picture_gallery, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

2 个答案:

答案 0 :(得分:0)

要将选定的图片从Gallery传递到Main,您应该使用startActivityForResult()代替startActivity()

请参阅http://developer.android.com/reference/android/app/Activity.html#StartingActivities

答案 1 :(得分:0)

听起来我应该像这样使用偏好。您可以将resourceID的int存储在首选项对象中。当您加载主要活动时,您将尝试获取该首选项值,然后将背景图像更改为该值。

在您的图库中,当用户选择图片时,您将资源ID保存为首选项。

public class MainActivity extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   int resourceId = settings.getInt("backgroundImage", DEFAULT_VALUE);

   // Now use that ID to set the background 
}

....

}

public class PictureGallery extends Activity {
    ...
    protected void onCreate(Bundle savedInstanceState) {
       ...
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
           ...
           SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
           SharedPreferences.Editor editor = settings.edit();
           editor.putBoolean("backgroundImage", DEFAULT_VALUE);

          // Commit the edits!
          editor.commit();

有关使用共享偏好的详情,请参阅http://developer.android.com/reference/android/content/SharedPreferences.html

编辑:此解决方案将允许选择在应用程序的启动之间保持不变。您将永久更改背景。如果您只是想暂时更改它,那么如另一个答案所示,您想使用startActivityForResult