Programing

프로그래밍 방식으로 TextView에서 왼쪽 드로어 블을 설정

lottogame 2020. 4. 2. 08:10
반응형

프로그래밍 방식으로 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

반응형