Sometimes it is necessary to change the default application font on your own. How to do it, I'll show in this article.
Create a
layout with a set TextView, on which to experiment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt_font_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/txt_font_1"
android:textSize="20sp" />
<TextView
android:id="@+id/txt_font_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/txt_font_2"
android:textSize="20sp" />
<TextView
android:id="@+id/txt_font_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/txt_font_3"
android:textSize="20sp" />
</LinearLayout>
In the
string resources necessary to add the following lines:
<string name="txt_font_1">Font Example 1</string>
<string name="txt_font_2">Font Example 2</string>
<string name="txt_font_3">Font Example 3</string>
Create a
new class FontSystem.
Add him to
the static attributes, once for each of our fonts:
public static final int TYPE_FONT_1 = 1; public static final int TYPE_FONT_2 = 2; public static final int TYPE_FONT_3 = 3;
And add a
method that will set the font to the desired View:
public static void setTypeface(View v, int type, Context context) { if (v == null) return; Typeface tf = null; try { switch (type) { case TYPE_FONT_1: tf = Typeface.createFromAsset(context.getAssets(),"fonts/font1.otf"); break; case TYPE_FONT_2: tf = Typeface.createFromAsset(context.getAssets(),"fonts/font2.otf"); break; case TYPE_FONT_3: tf = Typeface.createFromAsset(context.getAssets(),"fonts/font3.otf"); break; } if (v instanceof TextView) ((TextView)v).setTypeface(tf); }catch (Exception e) { e.printStackTrace(); } }
In general
Activity set fonts in our TextView:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); FontSystem.setTypeface(findViewById(R.id.txt_font_1), FontSystem.TYPE_FONT_1, this); FontSystem.setTypeface(findViewById(R.id.txt_font_2), FontSystem.TYPE_FONT_2, this); FontSystem.setTypeface(findViewById(R.id.txt_font_3), FontSystem.TYPE_FONT_3, this); }
Links
- The source codes of this project can be downloaded here: zip
No comments:
Post a Comment