您的位置:首页 > 其它

带图片(drawableXxx)的TextView

2015-12-20 17:12 288 查看

基本用法:

   

设置图片的核心其实就是:drawableXxx;可以设置四个方向的图片: drawableTop(上), drawableButtom(下), drawableLeft (左), drawableRight(右) 。另外,也可以使用drawablePadding来设置图片与文字间的间距!

效果图:



实现代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jay.example.test.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:drawableTop="@drawable/user_48"
android:drawablePadding="4dp"
android:gravity="center"
android:text="用户" />

</RelativeLayout>

图片大小设置:

Drawable在XML中无法直接设置其大小,需要在Java代码中来进行修改。
部分代码如下:

txt = (TextView) findViewById(R.id.txt);
Drawable[] drawable = txt.getCompoundDrawables();
// 数组下表0~3,依次是:左上右下
drawable[0].setBounds(100, 0, 200, 200);
txt.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]);


代码分析:

1.Drawable[] drawable = txt.getCompoundDrawables( ); 获得四个不同方向上的图片资源,数组元素依次是:左上右下的图。
2.drawable[1].setBounds(100, 0, 200, 200); 接着获得资源后,可以调用setBounds设置左上右下坐标点,比如这里设置了代表的是: 长是:从离文字最左边开始100dp处到200dp处 宽是:从文字上方0dp处往上延伸200dp!
3.txt.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]);为TextView重新设置drawable数组!没有图片可以用null代替哦! PS:另外,从上面看出我们也可以直接在Java代码中调用setCompoundDrawables为 TextView设置图片!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: