的attrs.xml文件中添加这个样式
我试图从"assetsfont"文件夹加载自定义字体
这是我的"TypefaceSingelton"类代码:
public class TypefaceSingelton {
private static TypefaceSingelton instance = new TypefaceSingelton();
private TypefaceSingelton() {}
public static TypefaceSingelton getInstance() {
return instance;
}
public static Typeface getFont() {
return Typeface.createFromAsset(AppContext.getAppContext().
getResources().getAssets(), "fonts/Myfont.otf");
}
}
和我的"AppContext"类:
public class AppContext extends Application {
public static Context context;
@Override
public void onCreate(){
super.onCreate();
AppContext.context = getApplicationContext();
}
public static Context getAppContext() {
return AppContext.context;
}
}
和我如何使用它在我的MainActivity:
public class MainActivity extends Activity {
private final Typeface FontTF = TypefaceSingelton.getFont();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final AutoCompleteTextView CtextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
CtextView.setTypeface(FontTF);
在"Typeface "处给出异常。
08-16 07:55:51.834: E/AndroidRuntime(3109): Caused by: java.lang.NullPointerException
08-16 07:55:51.834: E/AndroidRuntime(3109): at com.test.TypefaceSingelton.getFont(TypefaceSingelton.java:20)
08-16 07:55:51.834: E/AndroidRuntime(3109): at com.test.MainActivity.onCreate(MainActivity.java:133)
08-16 07:55:51.834: E/AndroidRuntime(3109): at android.app.Activity.performCreate(Activity.java:5104)
08-16 07:55:51.834: E/AndroidRuntime(3109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
我将使用"TypefaceSingelton"来避免性能下降
程序使用以下代码:
private final Typeface FontTF;
@Override
public void onCreate(Bundle savedInstanceState) {
Typeface FontTF = TypefaceSingelton.getFont();
你试过吗?
public static Typeface getFont() {
return Typeface.createFromAsset(AppContext.getAppContext().getAssets(),
"fonts/Myfont.otf");
}
注意Android不支持字体。font
为什么不使用一个自定义类TypefacedTextView来扩展AppCompatTextView,并为add type face属性创建styleable
public class TypefacedTextView extends AppCompatTextView {
public TypefacedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface);
setTypeFace(fontName);
styledAttrs.recycle();
}
public void setTypeFace(String fontName){
try{
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
setTypeface(typeface);
}catch (Exception e){
}
}
和这样的样式
<declare-styleable name="TypefacedTextView">
<attr name="typeface" format="string" />
</declare-styleable>
在目录res/values