TextView的一些高级应用(自定义字体、显示多种颜色、添加阴影)

        在我们Android日常的开发当中,TextView这个控件是很常用的一个控件,textvie的一些常规使用基本能满足项目需求,但是有时候会碰到一些比较复杂的问题,例如textvie显示多种颜色,添加阴影等等,话不多说直接进入主题吧!

1.    自定义字体

可以使用setTypeface(Typeface)方法来设置文本框内文本的字体,而android的Typeface又使用TTF字体文件来设置字体
所以,我们可以在程序中放入TTF字体文件,在程序中使用Typeface来设置字体:第一步,在assets目录下新建fonts目录,把TTF字体文件放到这里。第二步,程序中调用:

TextViewtv = (TextView)findViewById(R.id.textView);
AssetManagermgr=getAssets();//得到AssetManager
Typefacetf=Typeface.createFromAsset(mgr, "fonts/mini.TTF");//根据路径得到Typeface
tv.setTypeface(tf);//设置字体


2.textview的多种颜色

上图:


Android支持html格式的字符串,通过调用Html.fromHtml(str)方法可以转换html格式的字符串str。

代码也很简单,下面我就贴出源码。

package com.example.lyb.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;

public class TextViewDemoActivity extends AppCompatActivity {

    String textStr1 = "<font color=\"#DC143C\">第一种颜色,</font>";//支持换行操作可以在后面添加HTML换行</br>标签
    String textStr2 = "<font color=\"#4B0082\">第二种颜色,</font>";
    String textStr3 = "<font color=\"#0000CD\">第三种颜色,</font>";
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view_demo);
        textView= (TextView) findViewById(R.id.tv_demo_text_color);
        textView.setHint(Html.fromHtml(textStr1+textStr2+textStr3));

    }
}

布局文件很简单这里就不上传了!

3.textview的加粗

在xml布局文件中使用android:textStyle=”bold”可以将英文设置成粗体,但是不能将中文设置成粗体,将中文设置成粗体的方法是:使用TextPaint的仿“粗体”设置setFakeBoldText为true。



字体是不是比上面变粗了

示例代码如下:

textView.getPaint().setFakeBoldText(true);//中文加粗

4 添加阴影

在xml布局文件中使用一系列android:shadowXXX属性可添加设置阴影。具体为:shadowColor设置阴影颜色;shadowDx设置阴影水平偏移量;shadowDy设置阴影垂直偏移量;shadowRadius设置阴影半径。
示例代码:
android:shadowColor="#ffffff"
android:shadowDx="15.0"
android:shadowDy="5.0"
android:shadowRadius="2.5"



猜你喜欢

转载自blog.csdn.net/APPLYB/article/details/80347346