Android中TextView设置图标的方法

TextView可以设置左上右下4个图标,分为:布局和代码2种方式。

布局方式

<TextView
    android:id="@+id/txt_icon_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="26sp"
    android:textColor="#FFFFFFFF"
    android:drawableLeft="@drawable/ic_left"
    android:drawableTop="@drawable/ic_top"
    android:drawableRight="@drawable/ic_right"
    android:drawableBottom="@drawable/ic_bottom"
    android:drawablePadding="5dp"
    android:gravity="center"/>

注:
1.其中的drawableLeft、drawableTop、drawableRight、drawableBottom分别表示:左上右下的4个图标,drawablePadding表示文字与图标间的间距。
2.上述4个方位的图标,可以单独定义其中的某一个或几个。
3.此方式设置的图标只能按照图标本身的原始大小显示。

代码方式

textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_left, R.drawable.ic_top, R.drawable.ic_right, R.drawable.ic_bottom);
textView.setCompoundDrawablePadding(10);

注:
1.setCompoundDrawablesWithIntrinsicBounds方法的4个参数分别表示:左上右下的4个图标,setCompoundDrawablePadding方法表示文字与图标间的间距。
2.上述4个方位的图标,可以单独定义其中的某一个或几个。不显示图标的方位参数用0代替。
3.此方式设置的图标只能按照图标本身的原始大小显示。

Drawable drawableLeft = ContextCompat.getDrawable(mContext, R.drawable.ic_left);
drawableLeft.setBounds(0, 0, 32, 32);
Drawable drawableTop = ContextCompat.getDrawable(mContext, R.drawable.ic_top);
drawableTop.setBounds(0, 0, 32, 32);
Drawable drawableRight = ContextCompat.getDrawable(mContext, R.drawable.ic_right);
drawableRight.setBounds(0, 0, 32, 32);
Drawable drawableBottom = ContextCompat.getDrawable(mContext, R.drawable.ic_bottom);
drawableBottom.setBounds(0, 0, 32, 32);
textView.setCompoundDrawables(drawableLeft, drawableTop, drawableRight, drawableBottom);
textView.setCompoundDrawablePadding(10);

注:
1.setCompoundDrawables方法的4个参数分别表示:左上右下的4个图标,setCompoundDrawablePadding方法表示文字与图标间的间距。
2.上述4个方位的图标,可以单独定义其中的某一个或几个。不显示图标的方位参数用null代替。
3.此方式设置的图标,用户可以随意设置其大小。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值