在TextView 中如何添加圖片
第一種 在xml 文件中利用TextView的屬性開添加不同方位的圖片:
- <?xml version="1.0" encoding="utf-8"?>
- <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"
- android:background="#ccc"
- tools:context="com.lsc.yumo.textdemo.MainActivity">
- <!--drawableTop屬性:圖片在文字的上方-->
- <!--drawableRight:圖片在文字的右邊-->
- <!--drawableLeft:圖片在文字的左邊-->
- <!--drawableBottom:圖片在文字的下方-->
- <!--drawablePadding:圖片與文字的間距-->
- <TextView
- android:id="@+id/main_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:drawablePadding="10dp"
- android:drawableTop="@mipmap/ic_launcher"
- android:gravity="center"
- android:text="測試"
- android:textSize="18sp" />
- </RelativeLayout>
效果圖如下:
第二種方法 在java代碼中實現:
- public class MainActivity extends AppCompatActivity {
- TextView mainTv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mainTv = findViewById(R.id.main_tv);
- // 獲取圖片資源的Drawable對象
- Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
- // 設置圖片對象的位置和大小 這樣就可以更改圖片的大小
- drawable.setBounds(0,0,50,50);
- // 限定圖片資源在textView 中的位置 drawable在什麼位置 圖片就顯示在什麼位置
- // 在不需要顯示的位置設置爲null 如果在多個位置顯示則同時存在
- mainTv.setCompoundDrawables(drawable,null,null,null);
- // 設置圖片與文字之間的間距
- mainTv.setCompoundDrawablePadding(20);
- }
- }
效果圖如下: