我正在尝试将SD卡中的图像设置为ImageView
,但是它不起作用。我究竟做错了什么?我确定文件存在。
以下是 MainActivity
的代码:
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = findViewById(R.id.imageView);
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Naruto_newshot.png";
File file = new File(filePath);
if (file.exists())
imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
}
}
以下是 XML
布局的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
AndroidManifest.xml
:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mbo.testimage">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
最后图像200××149像素:
答案 0 :(得分:1)
您是否添加了写入外部存储的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 33);
}
}
答案 1 :(得分:0)
在您的清单中添加此权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
此外,在Android 6和更高版本上,您需要调用此命令以了解您是否具有权限
boolean permission = checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED;
如果不需要,请致电:
String[] perms = {"android.permission.READ_EXTERNAL_STORAGE"};
requestPermissions(perms, REQUEST_CODE);
最后,您需要重写此Activity方法,该方法将在用户响应后调用:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {}