set Text Drawable Left to TextView - Android User Interface

Android examples for User Interface:TextView

Description

set Text Drawable Left 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 setTextDrawableLeft(TextView txt, int padDip,
            int resId) {
        txt.setCompoundDrawables(getTextDrawable(txt.getContext(), resId),
                null, null, null);/*from  w  w w . j  a  v a  2  s.c  om*/
        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