TextView控件一般是用来显示文本的,而图片一般是用ImageView控件来显示,现在直接用textview来设置图片。
1.XML属性设置
最常见的一种方式,在控件的上下左右设置,可用
android:drawableLeft
android:drawableTop
android:drawableRight
android:drawableBottom
<TextView
android:id="@+id/textview_01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/ic_launcher"
android:text="hello_world" />
设置间距 android:drawablePadding="8dp"
2.代码动态设置
①可用setCompoundDrawables(null,null,null,null)
drawable = getResources().getDrawable(R.mipmap.launcher);
drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight()); // 必须要设置
textView.setCompoundDrawables(drawable, null, null, null); //括号里面的四个参数代表左上右下四个方向的图片,可以同时设置多个
②用setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
drawable = getResources().getDrawable(R.mipmap.launcher);
textView.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
textView.setCompoundDrawablePadding(5); // 设置间距
此方法就是把setCompoundDrawables在封装,内部实际就是调用setCompoundDrawables方法。不想设置图片,把四个参数都设置为null。