Иногда бывает необходимо поменять стандартный шрифт
приложения на свой собственный. Как это сделать, я покажу в этой статье.
Создадим макет с набором TextView, над которыми будем экспериментировать:
<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>
В строковые ресурсы надо добавить следующие строки:
<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>
Создадим новый класс FontSystem.
Добавим ему статические атрибуты, количество которых равно
количеству наших шрифтов:
public static final int TYPE_FONT_1 = 1; public static final int TYPE_FONT_2 = 2; public static final int TYPE_FONT_3 = 3;
И добавим метод, который будет устанавливать нужный шрифт в
нужное 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();
}
}
В основном Activity установим шрифты в наши 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);
}
Ссылки по теме
- Исходные коды данного проекта можно скачать отсюда: zip
Комментариев нет:
Отправить комментарий