Android使用代码为textview设置drawableLeft或drawableRight

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/ico_dianzan"
                android:gravity="center_vertical"
                android:text="0"
                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/jky_yihuangxing/article/details/78490730
今日推荐