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.此方式设置的图标,用户可以随意设置其大小。