TextView可以通过setCompoundDrawables来设置图片显示在文字的上下左右的地方,但是如何调整文字和图片的位置呢?
1.通过定义XML方式实现
- <TextView
- android:id="@+id/txtMsg"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:textSize="19px"
- android:gravity="center_horizontal"
- android:text="测试文字"
- android:drawablePadding="-20px" //设置字体和图片之间的距离, 这是实现文字叠加显示在图片之上的关键点~
- android:drawableTop="@drawable/ic_launcher" // 设置图片显示在文字的上方
- />
- TextView v = new TextView(this.getApplicationContext());
- v.setCompoundDrawablePadding(-20);
- v.setGravity(Gravity.CENTER_HORIZONTAL);
- Drawable image = getResources().getDrawable(icons[i]);
- image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());//非常重要,必须设置,否则图片不会显示
- v.setCompoundDrawables(null,image, null, null);
- v.setText("测试文字");
- v.setTextSize(TypedValue.COMPLEX_UNIT_PX,19);//设置字体大小为19px
-
-