将图像从资产目录复制到内部存储目录,并使用Android Studio的设备文件资源管理器在目录中成功找到新图像。但是UI是空白的。我在这里想念什么?
public class MainActivity extends AppCompatActivity {
Context context;
private final String assetImage = "qtest1.png";
boolean isDirectoryCreated;
private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImageView = findViewById(R.id.imageview);
context = getApplicationContext();
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(assetImage);
File dir = new File(context.getFilesDir().getAbsolutePath());
isDirectoryCreated = dir.mkdirs();
out = new FileOutputStream(dir + File.separator + "qtest1InStor.png");
copyFile(in, out);
} catch (IOException e) {
//
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
// NOOP
}
}
}
File imgInStor = new File(context.getFilesDir().getAbsolutePath() + File.separator + "qtest1InStor.png");
if (imgInStor.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgInStor.getAbsolutePath());
myImageView.setImageBitmap(bitmap);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="testpng" />
</androidx.constraintlayout.widget.ConstraintLayout>