在代码中设置drawableLeft

在xml中使用android:drawableLeft="@drawable/payicon_type";

实现 在控件左侧添加小图标。那么在代码中如何实现同样的效果呢?(上下左右同理)

Drawable drawable =  getResources().getDrawable(R.drawable.payicon_type);

/// 这一步必须要做,否则不会显示.
drawable.setBounds(0, 0, drawable.getMinimumWidth(),
drawable.getMinimumHeight());
editview.setCompoundDrawables(drawable,null,null,null);

//另外如果是用assets文件夹下的图片则是

Drawable drawable = FileUtil.getDrawableFromAssetFile(context, "payicon_type.png");

/**   * 从assets 文件夹中获取文件并读取图片资源    

* @param context

  * @param fileName  

* @return

  */

 public static Drawable getDrawableFromAssetFile(Context context,    String fileName) {

  BitmapDrawable drawable = null;

  try {

   InputStream is = context.getAssets().open(fileName);

  Bitmap image = BitmapFactory.decodeStream(is);   

 drawable = new BitmapDrawable(context.getResources(), image);   

 is.close();   

} catch (Exception e) {   }  

 return drawable;  

}

原文地址:https://www.cnblogs.com/yuan1225/p/3135742.html