Android应用开发使用第三方字体

来源:互联网 发布:浮雕软件 编辑:程序博客网 时间:2024/04/30 16:56

Android原生的字体可能不会让UI妹纸欢心,实在觉得它太丑了,于是乎UI妹纸就用了第三方字体作为APP的字体风格,这篇博客就是总结在Android应用开发中怎样使用第三方字体。

         首先得有第三方字体库,这里的字体库文件是black_simplified.TTF,在Android Assert目录下新建front文件夹,并将字体库文件放在front目录下面,即/Assert/front/black_simplified.TTF 

         这里来总结下怎样在应用中使用第三方字体才是最简便的。以TextView为例,API接口中有一个方法叫做setTypeface(Typeface obj),这就是设置TextView显示的字体样式的接口,那么怎样得到Typeface对象呢,查看API后可以由Typeface.creatFromAssert(obj)方式来获取,单个TextView使用第三方字体的整个流程如下:

public class MainActivity extends Activity {private Typeface TEXT_TYPE ;private TextView mTv ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 加载自定义字体try{TEXT_TYPE = Typeface.createFromAsset(getAssets(),"fronts/black_simplified.TTF"); }catch(Exception e){Log.i("MainActivity","加载第三方字体失败。") ;TEXT_TYPE = null ;}mTv = (TextView)findViewById(R.id.tv1) ;if(TEXT_TYPE != null){mTv.setTypeface(TEXT_TYPE) ;}mTv.setText("Android程序开发") ;}}

运行之后即可看到效果。但是这样是不是很麻烦?!要为每一个需要用到第三方字体的控件设置字体样式。这里的解决办法是重写需要使用第三方字体的控件,这里以TextView为例,当然Android中可以显示字体的控件还有很多,如Button、EditText。Android开发中常常需要实现自己的Application对象,因为它是全局的,也是程序最先执行的模块,也便于数据共享,所以,初始化字体的操作就放在我们自定义的Application子类MyApp中。代码片段如下:

在MyApp.java的onCreate函数中初始化自定义的typeface:

@Overridepublic void onCreate() {// 加载自定义字体try{TEXT_TYPE = Typeface.createFromAsset(getAssets(),"fronts/black_simplified.TTF"); }catch(Exception e){Log.i("MyApp","加载第三方字体失败。") ;TEXT_TYPE = null ;}super.onCreate();}

在AndroidManifest.xml文件中的<application>中注明name属性为自定义的Application子类:

<application        android:name="com.example.androidfronttypeface.MyApp"        ……</application>

自定义TextView:

public class MyFrontTextView extends TextView {public MyFrontTextView(Context context) {super(context);setTypeface() ;}public MyFrontTextView(Context context, AttributeSet attrs) {super(context, attrs);setTypeface() ;}public MyFrontTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);setTypeface() ;}private void setTypeface(){// 如果自定义typeface初始化失败,就用原生的typefaceif(MyApp.TEXT_TYPE == null){setTypeface(getTypeface()) ;}else{setTypeface(MyApp.TEXT_TYPE) ;}}}
Layout文件中需要引用自定义的TextView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent">    <com.example.androidfronttypeface.MyFrontTextView        android:id="@+id/tv1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text=”Android应用开发” /></RelativeLayout>

大概就是这样的,如果是Button或其他控件需要使用第三方字体,也是同样的道理。

源码参考








1 0
原创粉丝点击