set Text Drawable to TextView - Android User Interface

Android examples for User Interface:TextView

Description

set Text Drawable to TextView

Demo Code


//package com.java2s;
import android.content.Context;

import android.graphics.drawable.Drawable;

import android.util.DisplayMetrics;
import android.widget.TextView;

public class Main {
    public static void setTextDrawable(TextView txt, int padDip, int[] resId) {
        Drawable left = null, top = null, right = null, bottom = null;
        if (resId[0] != 0) {
            left = getTextDrawable(txt.getContext(), resId[0]);
        }/* w  w w.  j  av a  2s . c om*/
        if (resId[1] != 0) {
            top = getTextDrawable(txt.getContext(), resId[1]);
        }
        if (resId[2] != 0) {
            right = getTextDrawable(txt.getContext(), resId[2]);
        }
        if (resId[3] != 0) {
            bottom = getTextDrawable(txt.getContext(), resId[3]);
        }
        txt.setCompoundDrawables(left, top, right, bottom);
        if (padDip >= 0) {
            txt.setCompoundDrawablePadding(dp2Px(txt.getContext(), padDip));
        }
    }

    public static Drawable getTextDrawable(Context context, int resId) {
        Drawable drawable = context.getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        return drawable;
    }

    public static int dp2Px(Context context, float dp) {
        DisplayMetrics displayMetrics = context.getResources()
                .getDisplayMetrics();
        return (int) (dp * displayMetrics.density);
    }
}

Related Tutorials