2014-03-06 74 views
0

我想從圖庫中選擇圖像到ImageView,但它沒有工作。從圖片庫到圖像視圖的圖片

下面的代碼:

public class Profilo extends MainActivity { 

private ImageView img; 
private Bitmap bmp; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.profilo); 

    img = (ImageView)findViewById(R.id.profile_image); 

    img.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
      intent.setType("image/*"); 
      startActivityForResult(intent, 1); 
     } 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
      if (resultCode == RESULT_OK) { 
       String filePath = null; 
       if (requestCode == 1) { 
        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(); 

        if (bmp != null && !bmp.isRecycled()) { 
        } 
        bmp = null; 
       } 
       bmp = BitmapFactory.decodeFile(filePath); 
       img.setBackgroundResource(0); 
       img.setImageBitmap(bmp); 
      } 
      else 
      { 
       Log.d("Status:", "Photopicker canceled"); 
      } 
     } 
    }); 
} 

這裏的佈局:

<LinearLayout 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:weightSum="1"> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/profile_image" 
    android:contentDescription="@string/profile_image" 
    android:src="@drawable/profilo_facebook" 
    android:layout_gravity="center_horizontal"/> 

</LinearLayout> 

和這裏的清單:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.sidacri.testapp" > 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
<activity android:name=".Profilo" 
     android:label="@string/label_profilo"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN"/> 
      <category android:name="android.intent.category.LAUNCHER"/> 
     </intent-filter> 
    </activity> 
</application> 
</manifest> 

讓我知道哪來的問題,請:)我」我剛剛嘗試了一些方法,但它從來沒有doesen't工作

回答

0

有你的代碼的bug:

String filePath = null; 

所以你空值傳遞給你的DecodeFile法等你位圖爲空。如果要將圖像設置爲ImageView,則可以這樣做,而不必將其轉換爲Bitmap,如下所示:

YourImageView.setImageURI(selectedImageUri);