带图片的TextView:

在实际开发中,可能会遇到如下的需求:

带图片的TextView

要实现这种效果,一般的想法是:一个ImageView用于显示图片+一个TextView用于显示文字,

然后把它们丢进同一个LinearLayout中,接着依次创建四个这样的LinearLayout,再另外放到一个大的LinearLayout中即可实现效果。

但考虑到布局层次越少,性能越好,因此使用drawableXXX就可以省掉以上过程,直接设置四个TextView就可以完成需求。

 

基本用法:

设置四个方向上的图片:

drawableTop(),drawableButtom(),drawableLeft(),drawableRight()。除此之外,还可以使用drawablePadding来设置图片与文字之间的距离。

带图片的TextView

 

实现代码:

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:drawableTop="@drawable/head_image"

android:drawableLeft="@drawable/head_image"

android:drawableRight="@drawable/head_image"

android:drawableBottom="@drawable/head_image"

android:padding="10dp"

android:text="头像"/>

 

MainActivity.java:
 

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 

textView=(TextView)findViewById(R.id.textView);

//获得四个不同方向上的图片资源,数组元素依次是:左上右下

Drawable[]drawables=textView.getCompoundDrawables();

//数组下表0-3,依次是:左上右下

drawables[0].setBounds(0,0,100,100);

drawables[1].setBounds(0,0,100,100);

drawables[2].setBounds(0,0,100,100);

drawables[3].setBounds(0,0,100,100);

textView.setCompoundDrawables(drawables[0],drawables[1],drawables[2],

drawables[3]);

}

 

代码分析:
drawables[1].setBounds(0,0,100,100)

调用setBounds设置左上右下坐标点,比如这里设置了代表的是:

长:是从离文字最左边开始0dp处到100dp处,

宽:是从文字上方0dp处到往上延伸100dp处。

相关文章:

  • 2021-12-20
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
  • 2021-07-12
  • 2021-10-30
  • 2022-12-23
  • 2021-11-23
猜你喜欢
  • 2022-12-23
  • 2021-08-07
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2021-11-17
相关资源
相似解决方案