프로그래밍 방식으로 TextView에서 왼쪽 드로어 블을 설정
여기 xml에 textView가 있습니다.
<TextView
android:id="@+id/bookTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="@drawable/checkmark"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="24dip"
android:maxLines="1"
android:ellipsize="end"/>
보시다시피 DrawableLeft를 xml로 설정했습니다.
코드에서 드로어 블을 변경하고 싶습니다.
어쨌든이 일을해야할까요? 또는 텍스트보기를 위해 drawableLeft를 코드로 설정합니까?
setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)를 사용할 수 있습니다
이미지를 원하지 않는 곳에 0을 설정하십시오.
왼쪽의 Drawable에 대한 예 :
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
팁 : XML 속성을 알고 있지만 런타임시이를 사용하는 방법에 대한 실마리가 없을 때마다. 개발자 문서에서 해당 속성에 대한 설명으로 이동하십시오. 당신이 찾을 것입니다 관련 방법을 런타임시, 지원되는 경우. 즉 DrawableLeft
에서 여기에 나는 방법을 참조 setCompoundDrawablesWithIntrinsicBounds (INT, INT, INT, INT)이 이 작업을 수행하는 데 사용할 수 있습니다.
TextView에서 Drawable을 설정하기 위해 다음 방법 중 하나를 사용할 수 있습니다.
1- setCompoundDrawablesWithIntrinsicBounds (int, int, int, int)
2- setCompoundDrawables (왼쪽 그리기 가능, 위쪽 그리기 가능, 오른쪽 그리기 가능, 아래쪽 그리기 가능)
그리고 당신이 사용할 수있는 자원에서 끌어낼 수 있도록 :
getResources().getDrawable(R.drawable.your_drawable_id);
Kotlin 확장 + 드로어 블 주위에 일부 패딩
fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}
static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) {
int wi = drawable.getIntrinsicWidth();
int hi = drawable.getIntrinsicHeight();
int dimDiff = Math.abs(wi - width) - Math.abs(hi - height);
float scale = (dimDiff > 0) ? width / (float)wi : height /
(float)hi;
Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi));
drawable.setBounds(bounds);
return drawable;
}
참고 URL : https://stackoverflow.com/questions/6931900/programmatically-set-left-drawable-in-a-textview
'Programing' 카테고리의 다른 글
Docker의 이미지를 어떻게 삭제합니까? (0) | 2020.04.02 |
---|---|
쉘 스크립트에 전달 된 마지막 인수 얻기 (0) | 2020.04.02 |
JavaScript에서 정수를 이진수로 변환하는 방법은 무엇입니까? (0) | 2020.04.02 |
Error Domain = NSURLErrorDomain Code = -1005“네트워크 연결이 끊어졌습니다.” (0) | 2020.04.02 |
'cut'을 사용하여 마지막 필드를 찾는 방법 (0) | 2020.04.02 |