之前 在遇到图片下方带文字的时候,都是用两个控件来完成的,今天发现了一个属性,可以简单实现这个功能。
如下:
<TextView
android:id="@+id/iv_order_reserve"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="@color/white"
android:drawableTop="@drawable/icon_no_open"
android:gravity="center"
android:src="@drawable/icon_no_open"
android:text="@string/reservation" />
android:drawableTop="@drawable/icon_no_open"这个属性 可以设置图片显示的方向,上下左右。非常方便,而且不仅仅TexeView,button也是有这个属性的。
当然 如果我们要是在想在代码中,动态修改图片也很简单,如下:
Drawable drawable = getResources().getDrawable(R.drawable.male);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
tv_patient_name_content.setCompoundDrawables(null, null, drawable, null);
就可以,如果设置的drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());就是直接获取图片的大小来显示。
具体讲解下:
setBounds是设置画时候的起始位置,左上角位初始坐标。
setCompoundDrawables(left, top, right, bottom)
setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)
意思是设置Drawable显示在text的左、上、右、下位置。
但是这两个函数有区别,setCompoundDrawables 画的drawable的宽高是按drawable.setBound()设置的宽高,所以才有The Drawables must already have had setBounds(Rect) called. 使用之前必须使用Drawable.setBounds设置Drawable的长宽。
setCompoundDrawablesWithIntrinsicBounds是画的drawable的宽高是按drawable固定的宽高,所以才有The Drawables' bounds will be set to their intrinsic bounds. 即通过getIntrinsicWidth()与getIntrinsicHeight()获得,
记下来备忘,哈哈。