Android图像选择器ImageView无法正常工作

时间:2012-10-21 08:01:03

标签: android android-imageview bitmapfactory

我的Android应用程序挂起我选择图片的那一刻,没有例外,我无法理解为什么,请帮助代码在下面

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;
public class SelectPhoto extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photopick_layout);
        Button btn=(Button)findViewById(R.id.clickme);

        btn.setOnClickListener(this);


    }

     public void onClick(View arg0) {
           // TODO Auto-generated method stub
           Intent intent = new Intent(Intent.ACTION_PICK,
             android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
           startActivityForResult(intent, 0);
          }

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub

      super.onActivityResult(requestCode, resultCode, data);
      TextView textTargetUri = (TextView)findViewById(R.id.targeturi);
      if (resultCode == RESULT_OK){
       Uri targetUri = data.getData();
       textTargetUri.setText(targetUri.toString());
       Intent mi = new Intent(this , ImgDisplay.class);
       mi.putExtra(getString(R.string.app_name),targetUri);
       startActivity(mi);

      }

     }
     }

Imagedisplay活动这是它应该从其uri显示所选图像的部分

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class ImgDisplay extends Activity {
    private String a;

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

 a =getIntent().getStringExtra(getString(R.string.app_name));




 Uri myUri = Uri.parse(a);

 ImageView b=(ImageView) findViewById(R.id.image_view);
 Bitmap myBitmap = BitmapFactory.decodeFile(a);
 b.setImageBitmap(BitmapFactory.decodeFile(a));
 b.setImageBitmap(myBitmap);



    }

}

照片选择布局这是第一个要求您从gallary中选择图像的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
   android:background="#00AEC5">

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

    <TextView
  android:id="@+id/targeturi"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />

 <Button android:id="@+id/clickme" 
 android:text="@string/pick" 
 style="@style/style1"
android:layout_centerInParent="true"
 ></Button>


  </RelativeLayout>
</LinearLayout>

** Image_display layout *这是显示图像的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
   android:background="#00AEC5">

    <ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  

  ></ImageView>
</LinearLayout>

我确信这很容易,但我是新手

3 个答案:

答案 0 :(得分:0)

你应该在onActivityResult(例如here)中检查requestCode,如果它属于你的请求,则处理结果,如果不是,则调用super。

答案 1 :(得分:0)

使用

  

Intent.ACTION_GET_CONTENT

代替。这是我的图像选择器代码完美无缺。

public class GalleryActivity extends Activity {

static Bitmap bmp;
ImageView GalImg;
Uri imageUri;
protected static final int PHOTO_PICKED = 0;
// values for scaling image
    protected int outputX = 320;
    protected int outputY = 480;
    protected int aspectX = 2;
    protected boolean scale = true;
    protected int aspectY = 3;
    Bundle extra;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i("gal", "oncreate");
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.gallery_screen);
     extra = getIntent().getExtras();
    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.putExtra("crop", "true");
    photoPickerIntent.putExtra("aspectX", aspectX);
    photoPickerIntent.putExtra("aspectY", aspectY);
    photoPickerIntent.putExtra("outputX", outputX);
    photoPickerIntent.putExtra("outputY", outputY);
    photoPickerIntent.putExtra("scale", scale);
    File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");      
    photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, PHOTO_PICKED);

}

@Override
protected void onActivityResult(int requestCode, int resultcode, 
        Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);
    Log.i("gal", "onActivity");
    if (requestCode == 0) {

        if (intent != null && resultcode == RESULT_OK) {
            Log.i("gal", "if request ok");
            //Uri selectedImage = intent.getData();// fetching uri of selected image                                                        // image


            //Bitmap bMap = (Bitmap) intent.getExtras().get("data");

            /*String[] filePathColumn = { MediaStore.Images.Media.DATA };// string data of image                                                                            // containing

            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            // The cursor query returns with the path, but you don't know
            // which column it's in until you use the columnIndex code.
            // That simply gets the number of the column based on its name,
            // the same one used in the filtering process.
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);// file path of image

            cursor.close();//Closes the Cursor, releasing all of its resources 


            bmp = BitmapFactory.decodeFile(filePath);*/

            //saving this bitmap into static photo which will have camera pic if camera is called otherwise gallery 
            //is selected and gallery image gets saved in it

            //PlayMenuActivity.photo=bmp;========
            //PlayMenuActivity.photo=bMap;


             Uri selectedImage = imageUri;
             getContentResolver().notifyChange(selectedImage, null);                
             ContentResolver cr = getContentResolver();
             Bitmap bitmap;
             try {
                 bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);  
                 PlayMenuActivity.photo=bitmap;
                 Log.i("gal",String.valueOf(bitmap));
                 Log.i("photo", "data.getAction() is not null. setting image.");

             } catch (Exception e) {
                 //Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
                 Log.i("photo", e.toString());
             }

            Intent i=new Intent(GalleryActivity.this,ShowActivity.class);
            i.putExtra("category","gallery");
            startActivity(i);



        } else {
            Log.i("Status:", "Photopicker canceled");
        }

    }
}

希望这会有所帮助。

答案 2 :(得分:0)

好的,谢谢大家,我知道它的可耻但唯一的问题是我忘了在清单文件中包含“ImgDisplay”活动:)否则代码工作得很好:D