我正在尝试在不同的 Activities
中应用自定义字体,现在我在 onCreate()
中有以下代码在我的 MainActivity
:
String fontTitle = "fonts/OpenSans-Bold.ttf";
Typeface titleFont = Typeface.createFromAsset(getAssets(), fontTitle);
page_title.setTypeface(titleFont);
我想知道是否可以制作 Typeface
public 这样我就可以在其他 Activity 中访问它。
我创建了一个名为 FontHelper
的类:
public class FontHelper extends MainActivity {
// path for the fonts
String fontTitle = "fonts/OpenSans-Bold.ttf";
Typeface titleFont = Typeface.createFromAsset(getAssets(), fontTitle);
}
但在其他Activities
当我使用 textView.setTypeface(FontHelper.titleFont)
我得到一个错误。我该如何解决这个错误?
最佳答案
您可以使用静态工厂方法为每个 Activity
创建您的 Typeface
实例,如下所示:
public class FontHelper {
private static final String FONT_PATH = "fonts/OpenSans-Bold.ttf";
public static Typeface getCustomTypeFace(Context context) {
return Typeface.createFromAsset(context.getAssets(), FONT_PATH);
}
}
你可以这样使用它:
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Typeface typeface = FontHelper.getCustomTypeFace(this);
...
}
}
关于java - Android中制作一个public类型的人脸方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37017471/