개발/Android
TextView 에 이미지 포함하기
Lumasca
2021. 8. 26. 13:34
텍스트와 이미지가 함께 구성하는 경우가 종종 발생한다. ImageView를 별도로 구성하지 않고 TextView의 속성을 이용하면 쉽게 처리할 수 있다.
아래는 layout XML 의 내용이다.
root layout 태그에 xmlns:app="http://schemas.android.com/apk/res-auto" 를 추가한다.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
보통 왼쪽 오른쪽에 추가하는 케이스가 많은데 오른쪽은 app:drawableEndCompat, 왼쪽은 app:drawableStartCompat 을 이용하면 된다. 그리고 텍스트와 이미지 사이 간격은 android:drawablePadding 으로 조절한다.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/font_medium"
android:includeFontPadding="false"
android:text="더보기"
android:textAppearance="@style/Text14White"
app:drawableEndCompat="@drawable/icon_angle_greater"
app:drawableStartCompat="@drawable/icon_info"
android:drawablePadding="10dp"
/>
소스코드로 설정할 경우, TextView의 setCompoundDrawables(left, top, right, bottom) 메소드를 이용해서 drawable을 원하는 위치에 설정해주면 된다.
val iconInfo = ContextCompat.getDrawable(requireContext(), R.drawable.icon_info)
val iconBracket = ContextCompat.getDrawable(requireContext(), R.drawable.icon_angle_greater)
binding.tvPoint.setCompoundDrawables(icon, null, iconBracket, null)