我想肯定会帮助你是更简单的方法
Java版本:
import static android.app.Activity.RESULT_OK;
private Bitmap bitmap;
private Uri filePath;
private void showFileChooser() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GET_IMAGE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
imageView1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
科特林版本:
import android.app.Activity.RESULT_OK
private val GET_IMAGE = 1
private lateinit var filePath : Uri
private lateinit var bitmap : Bitmap
private fun selectImage() {
var photoPickerIntent : Intent = Intent(Intent.ACTION_PICK)
photoPickerIntent.setType("image/*")
startActivityForResult(photoPickerIntent, GET_IMAGE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == GET_IMAGE && resultCode == RESULT_OK && data != null){
filePath = data.data
try{
bitmap = MediaStore.Images.Media.getBitmap(activity!!.contentResolver, filePath)
imageView!!.setImageBitmap(bitmap)
}catch (exception : IOException){
Toast.makeText(activity,"Error Loading Image!!!", Toast.LENGTH_SHORT).show()
}
}
}