
图像视图展示的图片通常位于res/drawable***目录,设置图像视图的显示图片有两种方式:
(1)在XML文件中,通过属性android:src设置图片资源,属性值格式形如“@drawable/不含扩展名的图片名称”。
(2)在Java代码中,调用setImageResource方法设置图片资源,方法参数格式形如“R.drawable.不含扩展名的图片名称”。

添加了src属性的ImageView标签示例如下:
<ImageView android:id="@+id/iv_scale" android:layout_width="match_parent" android:layout_height="220dp" android:src="@drawable/apple" />
给图像视图设置图片资源的代码例子如下所示:
// 从布局文件中获取名叫iv_scale的图像视图
ImageView iv_scale = findViewById(R.id.iv_scale); iv_scale.setImageResource(R.drawable.apple); // 设置图像视图的图片资源

ImageView本身默认图片居中显示,若要改变图片的显示方式,可通过scaleType属性设定,该属性的取值说明如下:


布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_scale"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_marginTop="5dp"
android:src="@drawable/apple" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_fitCenter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="fitCenter"
android:te

本文详细讲解了Android中ImageView和ImageButton的区别,展示了如何设置图片显示、缩放类型,以及如何在两者间实现文本与图片的组合。还介绍了在两种控件中设置图片位置的不同方式,适合理解和应用到实际项目中。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



