我知道關於此主題還有其他幾個問題,但沒有一個解決方案適用於我。我在清單中添加了權限。我可以打開畫廊選擇一張照片並返回到應用程序,但imageView不會更改。該應用正在做一些處理,我沒有得到任何錯誤。我試圖在將圖像插入到imageview之前嘗試縮放圖像,但沒有運氣。從圖片庫上傳的圖片不會顯示在ImageView中
這裏是我的代碼:
public class UserDetailsFragment extends Fragment {
private Context context;
private ImageView imageView;
private Bitmap uploadedImage;
public static final int RESULT_IMAGE = 0;
public UserDetailsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_user_details, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState){
imageView = (ImageView) getView().findViewById(R.id.profile_picture);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_IMAGE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
try {
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(uploadedImage);
}catch (Exception ex){
}
}
}
}
這裏是我的ImageView:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="-160dp"
android:layout_gravity="center"
android:layout_below="@+id/imageView"
android:src="@drawable/user_details_icon"
android:id="@+id/profile_picture" />
編輯
我試圖用畢加索代替,但仍然沒有運氣:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Picasso.with(context)
.load(MediaStore.Images.Media.DATA)
.resize(10, 10)
.centerCrop()
.into(imageView);
}
首先,**不要在沒有記錄它的情況下捕獲一個'Exception',因爲你是'onActivityResult()'。其次,您的'onActivityResult()'代碼是錯誤的,因爲您可能無權處理文件路徑(例如,它指向可移動存儲),並且您正在主應用程序線程上執行磁盤I/O。使用[圖像加載庫](https://android-arsenal.com/tag/46),像[Picasso](https://github.com/square/picasso),將'Uri'傳遞給正確使用'Uri'並且異步填充'ImageView'。 – CommonsWare
感謝您的提示。我對Android相當陌生,所以我實際上並不瞭解畢加索。我不確定我明白你的意思onActivityResult(),但我試圖改變它到內部存儲,而不是仍然沒有運氣。我也改變了我的整個onActivityResult(見編輯),但仍然沒有運氣 – Andypandy