android textview在code(代码)中设置图片 和XML设置图片

给大家提供一些方法,大家可以直接拿去使用,textview在code{代码}中设置上下左右设置图片。有几种方法,这个给大家列举一些。

下面方法建议放在util工具类中,其中的好处就不用我多讲了。

 

,//资源ID public static void setTextDrawable(Context context, int drawableRes,//资源ID
   TextView tvName) {
  Drawable drawableTop = context.getResources().getDrawable(drawableRes);
  // 必须设置图片大小,否则不显示
  drawableTop.setBounds(0, 0, drawableTop.getMinimumWidth(),
    drawableTop.getMinimumHeight());
  tvName.setCompoundDrawables(null, drawableTop, null, null);
 }

//bitmap,

 public static void setTextDrawable(Context context, Bitmap bitmap,
   TextView tvName) {
  Drawable drawableTop = BitmapUtils.bitmap2Drawable(bitmap);
  // 必须设置图片大小,否则不显示
  drawableTop.setBounds(0, 0, drawableTop.getMinimumWidth(),
    drawableTop.getMinimumHeight());
  tvName.setCompoundDrawables(null, drawableTop, null, null);
 }


//网络URL路径

 public static void setTextDrawable(Context context, String url,
   final TextView textView) {
  ImageLoader.getInstance().loadImage(url, new ImageLoadingListener() {
   public void onLoadingStarted(String arg0, View arg1) {
   }

   public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
   }

   public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
    Drawable drawableTop = BitmapUtils.bitmap2Drawable(bitmap);
    // 必须设置图片大小,否则不显示
    drawableTop.setBounds(0, 0, drawableTop.getMinimumWidth(),
      drawableTop.getMinimumHeight());
    textView.setCompoundDrawables(null, drawableTop, null, null);
   }

   public void onLoadingCancelled(String arg0, View arg1) {
   }
  });
 }

以上共有三个方法,每个方法针对的要设置的都不相同。若有其他问题,希望各位大神多多指点。


如果要是想之间在XML中设置图片的话,那只需要一句话就可以了        android:drawableTop="@drawable/ic_launcher"