TextView设置drawableLeft,drawableRight,drawableTop和drawableBottom
2017-07-21 15:12
453 查看
需求:
效果图
需求分析:
看到这样的需求,我们一般有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);
再来看效果图:
说了这么多,给Top,Right,Bottom和4个位置都设置你会了吗?
相关文章推荐
- 【Android】TextView动态设置android:drawableLeft|Right|Top|Bottom,SetColor
- TextView 代码设置drawableLeft、drawableRight、drawableTop、drawableBottom
- TextView,Button的DrawableLeft,,Right 使用代码动态的设置
- Android动态布局,并动态为TextView控件设置drawableLeft、drawableRight等属性添加图标
- EditText设置DrawableRight,DrawableLeft,DrawableTop... 点击事件
- 使用代码为TextView或者Button设置drawableLeft,top,ringht,buttom
- android关于TextView的drawableLeft,drawableTop,drawableRight,drawableRight的drawable大小及位置问题
- TextView中设置drawableLeft、drawableRight时设置图片的大小方法
- Android使用代码为textview设置drawableLeft或drawableRight
- Android动态布局,并动态为TextView控件设置drawableLeft、drawableRight等属性加入图标
- Android控件设置——动态View的drawableLeft/ drawableRight/drawableTop/drawableBottom
- Android动态布局,并动态为TextView控件设置drawableLeft、drawableRight等属性添加图标
- 关于在TextView中设置DrawableLeft,DrawableRight等不显示的问题
- 关于在TextView中设置DrawableLeft不显示的问题
- 安卓在代码中设置TextView的drawableLeft、drawableRight、drawableTop、drawableBottom
- 动态设置android:drawableLeft|Right|Top|Bottom
- Android 自定义view-如何设置TextView drawableLeft 图片大小?
- TextView代码设置一个TopDrawable
- 设置drawableTop、drawableLeft、drawableRight、drawableBottom图片大小
- Android TextView 代码中设置DrawableLeft 图片