需求:
效果图
需求分析:
看到这样的需求,我们一般有3种解决方案:
- 左边放一个ImageView右边紧跟着一个TextView;
- 放一个TextView通过SpannableString类来帮助处理,我想也是可以做到的
- 放一个TextView,通过drawableLeft/Right/Top/Bottom来处理。
经过考量,第一种方案太low,第二种方案适合处理更复杂的文本,比如有部分内容点击事件,改变部分字体颜色等等,所以选择第三种方案即可满足需求了。说这么多纯属装逼。
实现方式2种:
- 通过xml布局直接写入,不灵活,但是方便,代码量少;
- 通过java代码,可以实现灵活控制
先说第一种方案:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="@mipmap/test"
android:text="通过XML测试TextView的DrawableLeft功能"/>
看效果:
第二种方案的布局(没有drawableLeft的属性啊):
<TextView
android:id="@+id/tv_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="通过JAVA代码测试TextView的DrawableLeft功能"/>
效果:
好,下面通过java代码完成逆袭:
TextView tv_left = (TextView) findViewById(R.id.tv_left);
//首先获取到drawable对象
Drawable drawable = getResources().getDrawable(R.mipmap.test);
//public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top,@Nullable Drawable right, @Nullable Drawable bottom)
//一共有左,上,右,下四个位置,如果不想设置图标就直接给null好了
tv_left.setCompoundDrawables(drawable, null, null, null);
wfc居然没效果:
好吧,原来需要加上这一句:
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
再来看完整代码:
TextView tv_left = (TextView) findViewById(R.id.tv_left);
//首先获取到drawable对象
Drawable drawable = getResources().getDrawable(R.mipmap.test);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
//public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top,@Nullable Drawable right, @Nullable Drawable bottom)
//一共有左,上,右,下四个位置,如果不想设置图标就直接给null好了
tv_left.setCompoundDrawables(drawable, null, null, null);