目前我正在开发一个需要在我的活动中使用浏览按钮的应用程序。当我按下浏览按钮时,我应该能够浏览我的 SD 卡和手机内存中的图像文件。点击图像文件后,它应该被选中,图像文件的路径(即所选图像文件所在的位置)应该显示在文本视图的活动中。所选图像也应显示在图像视图中。这个怎么做?有人可以帮帮我吗..
以下解决方案的致谢:如何在 Android 应用程序中从图库中选择图像 Viral Patel。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"></ImageView>
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Load Picture"
android:layout_gravity="center"></Button>
</LinearLayout>
package com.example.yourpackage;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.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 && resultCode == RESULT_OK && null != data) {
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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
在清单中添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MediaStore.Images.Media.DATA
已弃用。所以@Looking_Forward 兄弟的代码将无法在 android 10+ 上运行。但只需简单修改,我就可以使用@Looking_Forward 兄弟的代码。过程如下:
在
Uri selectedImage = data.getData();
行之后删除所有代码并只使用Glide.with(this).load(selectedImage).into(imageView)
(这是Glide库)。此外,使用 contentProvider(@Looking_Forward 兄弟显示)也容易得多。