您的位置:首页 > 移动开发 > Android开发

Android-自定义TextView ,打破常规默认TextView

2016-07-22 17:27 471 查看

序:有时候UI设计常常会在界面设计中加入与设计风格相搭配的字体,而作为APP开发的我们一般都会引用默认的TextView字体进行显示;今天就来写一篇自定义字体的文章!

PS:别忘了向UI要ttf字体文件哦



1 在工程目录下创建assets 文件夹,将ttf字体文件copy到该文件下



我这里从电脑字体库里面随便拿了三种字体,楷书、行楷、隶书 (控制器面板,字体就找到系统字体库了)

2 创建自定义TextView

2.1 自定义字体View继承TextView 实现三个构造器

public class KaitiTextView extends TextView {

public KaitiTextView(Context context) {
super(context);
}

public KaitiTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public KaitiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}


2.2 获取字体文件构造器中初始化字体

private void init(Context context)
{
Typeface roboto= Typeface.createFromAsset(context.getAssets(),"STKAITI.TTF");
this.setTypeface(roboto);
}


2.3 完成自定义TextView

public class KaitiTextView extends TextView {

public KaitiTextView(Context context) {
super(context);
init(context);
}

public KaitiTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}

public KaitiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}

private void init(Context context)
{
Typeface roboto= Typeface.createFromAsset(context.getAssets(),"STKAITI.TTF");
this.setTypeface(roboto);
}
}


3 在布局文件中引用自定义的TextView

<LinearLayout 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"
android:orientation="vertical"
tools:context=".ui.MainActivity">

<com.hengda.smart.blueamer.textview.KaitiTextView
android:id="@+id/tv_kaiti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="23sp" />

<com.hengda.smart.blueamer.textview.XinkaiTextView
android:id="@+id/tv_xingkai"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="23sp"/>

<com.hengda.smart.blueamer.textview.KaitiTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="23sp"
android:text="举头望明月"/>

<com.hengda.smart.blueamer.textview.XinkaiTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="23sp"
android:text="低头思故乡"/>

<com.hengda.smart.blueamer.textview.LitiTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="23sp"
android:text="   人生本就该简简单单的做好每时每刻的自己,而不应该把过多的期望,放在未来,因为时光是最无情的东西。先不说未来的人或事的改变,说不定未来变的是你自己。现在的你,或许颓废不堪,或许满怀斗志,或许忙忙碌碌,或许无所事事。但未来的你会是怎样,谁知道呢?"/>

</LinearLayout>


4 完成了自定义TextView 的显示

是不是很简单呢?

SampleCode:https://github.com/BlueAmberTec/BlueAmerTj_TextView
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  textview