Android 一个TextView轻松搞定图片和文字同时显示

Talk is cheap , show you the code!

1.我们用xml为TextView设置图片的时候,通常写法都是这样写的

<TextView 
android:id="@+id/favort" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginRight="18dp" 
android:drawablePadding="6dp" 
android:drawableRight="@mipmap/xxx" 
android:gravity="center_vertical" 
android:text="0xxx" 
android:textSize="12sp"/>

2.需求场景,电量发生变化的时候,需要在代码里改变电量图片,这时候就需要考虑用代码动态设置了:

if (datas.get(position).isPraised()) {
 Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ico_dianzan_selected); // 这一步必须要做,否则不会显示. 
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); 

favort.setCompoundDrawables(null, null, drawable, null); 
} else { 
    Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ico_dianzan); 
    // 这一步必须要做,否则不会显示. 
    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());             

favort.setCompoundDrawables(null, null, drawable, null); 
}

最后完美解决

有老铁说用ImageView+TextView 也可以实现点赞,当然这也是可以的,不过这样多了包裹关系,一个TextView 能搞定的,何必复杂实现呢,哈哈哈哈哈。。。。。。

猜你喜欢

转载自blog.csdn.net/mawei7510/article/details/88535230