我想在手机图库的图像视图中加载图像,我有 写了代码 的java:
public class MainActivity extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
Button btnTry , btnAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = findViewById(R.id.btnAdd);
btnTry = findViewById(R.id.btnTry);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//The integer argument is a "request code" that identifies your request. When you receive the result Intent,
// the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i ,RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data){
Uri selectImage = data.getData();
String[] filePathcolumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectImage , filePathcolumn , null , null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathcolumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView ivMemeImage = findViewById(R.id.ivMemeImage);
ivMemeImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
当我运行应用程序并点击添加按钮时图像未加载到图像视图中。 我已经在清单中给出了读写权限。
答案 0 :(得分:0)
您可以使用Uri显示图像。您只需设置imageView.setImageUri(selectedImage)
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
your_imageView.setImageURI(selectedImage);
}
答案 1 :(得分:-1)
这是你在android studio中完成的代码吗?
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data)
应该是
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && data!=null)
您的代码应该给您编译时错误
答案 2 :(得分:-2)
查看Picasso图书馆.. http://square.github.io/picasso/
使用一行代码将图像从URI加载到imageview中:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);