Skip to content

Instantly share code, notes, and snippets.

@subinkrishna
Created April 10, 2016 21:05
Show Gist options
  • Save subinkrishna/c22465668ac0f0fb423778e3ea695305 to your computer and use it in GitHub Desktop.
Save subinkrishna/c22465668ac0f0fb423778e3ea695305 to your computer and use it in GitHub Desktop.
TextView Binder using Android data binding library - custom font & compound drawable tinting
import android.content.res.AssetManager;
import android.databinding.BindingAdapter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.util.Log;
import android.widget.TextView;
/**
* @author Subinkrishna Gopi
*/
public class TextViewBinder {
/** Log tag */
private static final String TAG = TextViewBinder.class.getSimpleName();
@BindingAdapter({"bind:font"})
public static void setFont(TextView view, String fontName) {
Typeface currentTypeface = view.getTypeface();
int style = (null != currentTypeface) ? currentTypeface.getStyle() : Typeface.NORMAL;
Log.d(TAG, String.format("Bind - font: %s, style: %d, Text: %s",
fontName, style, view.getText()));
String typefaceName = "";
switch (style) {
case Typeface.NORMAL: typefaceName = "OpenSans-Regular"; break;
case Typeface.BOLD: typefaceName = "OpenSans-Bold"; break;
case Typeface.ITALIC: typefaceName = "OpenSans-Italic"; break;
case Typeface.BOLD_ITALIC: typefaceName = "OpenSans-BoldItalic"; break;
}
AssetManager am = view.getContext().getAssets();
Typeface tf = Typeface.createFromAsset(am, "fonts/" + fontName + "/" + typefaceName + ".ttf");
view.setTypeface(tf);
}
@BindingAdapter({"bind:colorTint"})
public static void setDrawableTint(TextView view, int color) {
Log.d(TAG, "Bind - tint: " + color);
Drawable d = DrawableCompat.wrap(view.getCompoundDrawables()[0]).mutate();
DrawableCompat.setTint(d, color);
view.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment