Tutorial details

Android TextView with custom fonts | App Code for Sale | Preview

Android TextView with custom fonts | Android Tutorial

How to use a custom font on a TextView

Overview PAGE TOP

While developing an android app I found that everytime I was trying to use a custom font on a TextView I copied the same lines:

1   TextView textview = (TextView) findViewById(R.id.text);
2   textview.setTypeface(...)

Obviously, that’s unnecessary and repetitive. Why not just create a custom view? And more, why not adding the font through xml code?

01  public class CustomTextView extends TextView {
02  
03    private Context mContext;
04      private String mFont;
05       
06      public CustomTextView(Context context) {
07          super(context, null);
08          mContext = context;
09          init();
10      }
11  
12      public CustomTextView(Context context, AttributeSet attrs) {
13          super(context, attrs);
14          mContext = context;
15          TypedArray a = context.getTheme().obtainStyledAttributes(
16                  attrs,
17                  R.styleable.CustomButtom,
18                  0, 0);
19          try {
20              mFont = a.getString(R.styleable.CustomButtom_font);
21          } finally {
22              a.recycle();
23          }
24          init();
25      }
26       
27      private void init() {
28          if (mFont != null) {
29              setTypeface(FontsUtils.get(mFont));
30          }
31      }
32  
33  }

We just have to extend from TextView and read from the attribute set the font string declared on its styleable resource. Just create an attrs.xml (or use an existing one) and add the following:

1   <declare-styleable name="CustomTextview">
2     <attr name="font" format="string" />
3   </declare-styleable>

Now, you could declare on your xml layout like this:

01  <LinearLayout
02    android:id="@+id/comments"
03    android:layout_width="match_parent"
04    android:layout_height="wrap_content" >
05    
06    <com.parkuik.android.ui.CustomTextView
07      android:layout_width="wrap_content"
08      android:layout_height="wrap_content"
09      android:text="@string/no_comments" />
10  </LinearLayout>

Reference PAGE TOP

http://www.javacodegeeks.com/2013/01/android-textview-with-custom-fonts.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.