对于我一直在开发的Android小部件,我正在尝试使用自定义字体。我在互联网上查了一些教程,我发现了几种方法。我选择了一个并试图实现它,但我得到一个错误,我无法弄清楚为什么。该技术使用一个单独的类(我已经发布了下面的代码)来设置字体。在这段代码中,我在setCustomFont的customFont行中出错。它说customFont无法解析为变量。有人可以帮我解释为什么会这样吗?
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TypefacedTextView extends TextView {
private static final String TAG = "TextView";
public TypefacedTextView(Context context) {
super(context);
}
public TypefacedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TypefacedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
String customFontl = a.getString(R.styleable.TypefacedTextView_typeface);
setCustomFont(ctx, customFont); // get an error here
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: " + e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
答案 0 :(得分:0)
String customFontl = a.getString(R.styleable.TypefacedTextView_typeface);
setCustomFont(ctx, customFont); // get an error here
您的变量声明为customFontl
(请注意最终l
),并且您尝试将其用作customFont
。我猜错误是customFont
没有定义或类似的东西,就像这样。
答案 1 :(得分:0)
我试过这可能它可以帮助你在这个代码中我的字体是在资产/字体文件夹中 如果它只在asseet中而不是代码字体/
中替换 public class MyTextView extends TextView{
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
rotate();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
rotate();
}
public MyTextView(Context context) {
super(context);
init();
rotate();
}
private void rotate() {
// TODO Auto-generated method stub
setSelected(true);
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/TrajanPro-Regular.otf");
setTypeface(tf);
}
}
}