zoukankan      html  css  js  c++  java
  • Android中自定义textview可以进行自体设置

    废话不说,下面是代码:

    package
    com.windy.androidfont; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; public class FontTextView extends TextView { private Context mContext; private String TypefaceName = ""; public String getTypefaceName() { return TypefaceName; } public void setTypefaceName(String typefaceName) { TypefaceName = typefaceName; Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); System.gc(); } public FontTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.mContext = context; int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0); if (resouceId != 0) { TypefaceName = context.getResources().getString(resouceId); } else { TypefaceName = attrs.getAttributeValue(null, "typefaceName"); } if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } public FontTextView(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; // 先判断是否配置的资源文件 int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0); if (resouceId != 0) { TypefaceName = context.getResources().getString(resouceId); } else { TypefaceName = attrs.getAttributeValue(null, "typefaceName"); } if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } public FontTextView(Context context) { super(context); this.mContext = context; // TypefaceName = attrs.getAttributeValue(null, "TypefaceName"); if (TypefaceName != null && !"".equals(TypefaceName)) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf"); this.setTypeface(typeface); } } }

    下面是布局:
    <com.example.androidfont.FontTextView
            android:id="@+id/fontTextView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="69dp"
            typefaceName="pop"
            android:text="FontTextView"
            android:textSize="30sp" />
    大字体是要设置的属性,pop是字体库的名字

    注意:自体库文件我这里放到了assets中的font文件夹中给个截图吧:

    strings.xml文件中的截图:可以把字体的配置放到字符串资源中,这样就能统一进行更改了,如果你的需要中要动态的进行配置的话,可以对FontTextView进行改写,我的想法是在将自体配置放进prefrence中进行配置,这样就可以直接在FontTextView中进行改写了,本来想把这个类写的完成呢,由于时间关系就没写,有需求的可以自己去实现。就说这么多吧。

    
    
    
     有需要代码的可以发邮件到我的邮箱:545099227@qq.com(QQ:545099227)
  • 相关阅读:
    WPS JS宏
    WPS基础
    算法文章收藏
    辩论赛
    物流系统
    C#导出excel复杂表格(单元各合并)
    VUE复杂表格合并
    Linux系统创建一个npm命令行工具
    Java使用技巧记录
    Ubuntu系统安装nodejs及npm
  • 原文地址:https://www.cnblogs.com/wangsx/p/3431636.html
Copyright © 2011-2022 走看看