Android中给textView添加一个图片,是一种很常见的需求,平时开发时,看到很多人其实对这块使用的并不好,这里给出一下使用方式
Android中给Textview增加图片分以下几步
- 生成
drawable对象 - 使用
drawable.setBounds(int left, int top, int right, int bottom)设置drawable的宽(right-left),高(bottom-top). - 使用
drawable.setBounds(int left, int top, int right, int bottom),设置图片位于Textview中的偏移,这个偏移需要结合图片放置到Textview中的位置来设置:例如我们要在Textview的开始处放置图片,left就表示图片距离Textview左边的距离。 - 设置文字与图片的距离
textview.compoundDrawablePadding = 2f.dp:对于放置在TextView左边的图片,就是图片的右边距具体文字开始处的间隔。 - 将图片设置到
Textview中
val drawable = ColorDrawable(Color.RED)
//图片的宽度是(120-70)dp,高度30dp, 偏移Textview左边70dp
drawable.setBounds(70f.dp, 0, 120f.dp, 30f.dp)
//图片和文字的间距为0dp
textview.compoundDrawablePadding = 0f.dp
//设置图片图片位于Textview的开始位置
textview.setCompoundDrawablesRelative(drawable, null, null, null)
236

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



