您的位置:首页 > 其它

使用TextView实现ImageView效果

2016-10-30 16:04 375 查看
要想TextView实现ImageView的效果,本质上还是加载的图片,只不过图片的格式变了,
从阿里巴巴矢量图库将需要的图片下载到购物车里,打开本地存储的位置,找到ttf结尾的文件,复制到项目的assets目录下,到这里初始化的工作就完成了,

此时java中需要做的是自定义类继承LayoutInflaterFactory,并重写其中的几个方法,



package com.example.user.demo.test;

/**
* Created by user on 2016/9/22.
*/publicclassIconFontLayoutFactoryimplementsLayoutInflaterFactory{

privatestatic Typeface mTypeface;
private AppCompatDelegate mAppCompatDelegate;
@Overridepublic View onCreateView(View parent, String name, Context context, AttributeSet attrs){
View view= mAppCompatDelegate.createView(parent,name,context,attrs);
if (view instanceof TextView) {
((TextView) view).setTypeface(mTypeface);
}

return view;
}

publicIconFontLayoutFactory(AppCompatDelegate mAppCompatDelegate,Context context){
if (mTypeface==null) {
mTypeface= Typeface.createFromAsset(context.getAssets(), "iconfont.ttf");
}
this.mAppCompatDelegate=mAppCompatDelegate;
}

}
//注意一定要在super.onCreate前调用。// 该方式可以在TextView及其子类对象创建完成时,就可以为其调用setTypeFace,非常的高效

然后再需要此功能的activity或者fragment中调用即可,调用方法如下,注意,必须在调用super.onCreat()之前执行该方法才会生效

LayoutInflaterCompat.setFactory(getLayoutInflater(),
new IconFontLayoutFactory(getDelegate(), this));
super.onCreate(savedInstanceState);setContentView(R.layout.activity_icon);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: