Created
September 6, 2017 10:23
-
-
Save AlexMeuer/fb38958e1f154a0fef4e9738df83a49c to your computer and use it in GitHub Desktop.
Basic extension of Android's TextView to allow declaring the use of custom fonts via xml. Assumes fonts are inside 'assets/fonts/' but this can be changed in `applyFont(..)`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="CustomFontTextView"> | |
<attr name="fontFile" format="string" /> | |
</declare-styleable> | |
</resources> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo.bar.baz; | |
import android.content.Context; | |
import android.content.res.TypedArray; | |
import android.graphics.Typeface; | |
import android.support.annotation.NonNull; | |
import android.util.AttributeSet; | |
import foo.bar.R; | |
/** | |
* TextView that just uses a specified font file from 'assets/fonts/'. | |
* Specify the font in xml with 'fontFile="my-font.ttf"' | |
*/ | |
public class CustomFontTextView extends android.support.v7.widget.AppCompatTextView { | |
public CustomFontTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
applyFont(attrs); | |
} | |
public CustomFontTextView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
applyFont(attrs); | |
} | |
private void applyFont(@NonNull AttributeSet attrs) { | |
final TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.CustomFontTextView); | |
try { | |
final String fontFile = attributes.getString(R.styleable.CustomFontTextView_fontFile); | |
final Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontFile); | |
setTypeface(font, getTypeface().getStyle()); | |
} finally { | |
attributes.recycle(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<foo.bar.baz.CustomFontTextView | |
android:id="@+id/foo_text" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:text="BAR!" | |
app:fontFile="Comic-Sans.ttf" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment