用android编写一个java语言imageView加载assets资源中的图片的事例,不要xml
时间: 2024-02-12 11:02:21 浏览: 92
好的,以下是一个简单的示例代码,可以用于在 Android 应用程序中使用 Java 代码加载 assets 目录中的图片到 ImageView 中:
```java
// 创建 ImageView 对象
ImageView imageView = new ImageView(this);
// 设置 ImageView 的布局参数
imageView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
// 从 assets 目录加载图片
try {
InputStream inputStream = getAssets().open("my_image.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 将 ImageView 添加到视图中
LinearLayout layout = new LinearLayout(this);
layout.addView(imageView);
setContentView(layout);
```
请注意,需要在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
另外,需要将图片文件放置在 assets 目录下。
阅读全文
相关推荐


















