将图像传递给另一个活动

时间:2010-08-23 03:55:13

标签: android android-intent bundle imageview

由于这个网站,我想出了如何在活动之间传递一个String值,但是我在传递图像方面遇到了麻烦。我想要的是让用户点击一个按钮,打开图库并允许选择图片。然后我有另一个按钮,打开另一个显示ImageView的活动。我希望能够将ImageView的图像从之前的活动中选择出来。

这是包含按钮的类,我点击该按钮打开图库并检索所选图像:

public class EnterEdit extends Activity implements View.OnClickListener 
{
private static final int SELECT_IMAGE = 0;

 String filepath;

 Bundle fieldresults;
 Intent b; 

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

  Button selectwallpaper = (Button) findViewById(R.id.selectwallpaper);
  selectwallpaper.setOnClickListener(this);

  Button previewwallpaper = (Button) findViewById(R.id.previewwallpaper);
  previewwallpaper.setOnClickListener(this);

  fieldresults = new Bundle();
  b = new Intent(this, PreviewScreen.class);
 }


 @Override
 public void onClick(View view) 
 {
  switch (view.getId())
  {
   case R.id.selectwallpaper:
    Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(gallery, SELECT_IMAGE);
    break;

   case R.id.previewwallpaper:
     startActivity(b); 
    }
    break;   
  }


 protected void onActivityResult(int requestCode, int resultCode, Intent data)
 {
  super.onActivityResult(requestCode, resultCode, data);

   if (resultCode == RESULT_OK)
   {
    if (requestCode == SELECT_IMAGE)
    {
     Uri selectedimage = data.getData();
     String[] filepathcolumn = {MediaStore.Images.Media.DATA};

     Cursor cursor = getContentResolver().query(selectedimage, filepathcolumn, null, null, null);
     cursor.moveToFirst();

     int columnindex = cursor.getColumnIndex(filepathcolumn[0]);
     filepath = cursor.getString(columnindex);
     cursor.close();

     fieldresults.putString("bitmap", filepath);
     b.putExtras(fieldresults);
    }
   }
 }
}

这是应该显示所选图像的类:

public class PreviewScreen extends Activity implements View.OnClickListener 
{

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

  Bundle fieldresults = this.getIntent().getExtras();
  String backgroundpath = fieldresults.getString("bitmap");

  String background = BitmapFactory.decodeFile(backgroundpath);
  ImageView gallerypic = (ImageView) findViewById(R.id.gallerypic);
  gallerypic.setImageBitmap(background); 
 }
}

如果我应该在OnActivityResult行中传递selectedImage或所选择的图像,我不确定是b.putExtra("bitmap", selectedimage);。我试过了两个,但我没有看到第二个活动的图像。另外,我在PreviewScreen课程中不确定我是否正确设置了imageview。任何帮助表示赞赏。感谢。

1 个答案:

答案 0 :(得分:2)

相信我,你不想在活动之间传递图像。相反,为什么不简单地传递图像的路径,让第二个活动决定如何处理该路径(在这种情况下解码并显示图像)。