View和ViewImage设置图片

1.view类的设置背景
android:background --setBackgroundResource(int) --A drawable to use as the background. 

setBackgroundDrawable(Drawable d)--- Set the background to a given Drawable, or remove the background.
相应的获取方法:
getBackground()---Gets the background drawable



2.ImageView类的设置背景
android:src-- setImageResource(int)---Sets a drawable as the content of this ImageView.

setImageDrawable(Drawable drawable)----Sets a drawable as the content of this ImageView.
相应的获取方法:
getDrawable()----Return the view's drawable, or null if no drawable has been assigned.

问:ImageView的src与background有什么区别呢?
用src的时候,应是原图显示,不该变图片的大小;用background的时候,按照组件的大小来放大或者缩小图片。


3.同一个ImageView中显示不同图片
有时候,我们为了在同一个ImageView中显示不同的图片,往往会使用:
  if(条件1) { 
       image.setBackground(R.id.xxx1); 
  } else if (条件2) { 
       image.setBackground(R.id.xxx2); 
  }
  可以用另一个简便的方法实现相同的功能,首先,在res/drawable下建立一个xml文件,内容如下:
  <level-list xmlns:android="http://schemas.android.com/apk/res/android">
       <item android:maxLevel="4"  android:drawable="@drawable/stat_sys_battery_0" />
       <item android:maxLevel="14"  android:drawable="@drawable/stat_sys_battery_10" />
       <item android:maxLevel="29" android:drawable="@drawable/stat_sys_battery_20" />
       <item android:maxLevel="49" android:drawable="@drawable/stat_sys_battery_40" />
       <item android:maxLevel="69"  android:drawable="@drawable/stat_sys_battery_60" />
       <item android:maxLevel="89" android:drawable="@drawable/stat_sys_battery_80" />
       <item android:maxLevel="100" android:drawable="@drawable/stat_sys_battery_100" />
  </level-list>
  然后在layout中把image view的src设置成已创建好的xml文件,程序中变换图片时,只需要使用:
  imageview.getDrawable().setLevel(50);
  Android会根据level的值自动选择对应的图片。手机显示剩余电量就是用这个方法来显示不同图片的。

路漫漫其修远兮 吾将上下而求索
原文地址:https://www.cnblogs.com/hudabing/p/3818399.html