我们只想说我想创建一个包含从assets文件夹中获取的所有字体的类,是否可能?
在不导入getAssets()
的情况下,我不允许我访问android.app.activity
。
公用事业类
import android.graphics.Typeface;
public class TypeFontAssets //possibly missing an extends?
{
public static Typeface cs = Typeface.createFromAssets(getAssets(), "fonts/ComicSans.ttf");
public static Typeface bh = Typeface.createFromAssets(getAssets(), "fonts/BradleyHand.ttf");
public static Typeface co = Typeface.createFromAssets(getAssets(), "fonts/Courier.ttf");
}
主要活动
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this class for ALL the fonts
TypeFaceAssets tfa = new TypeFaceAssets();
TextView userName = (TextView)findViewById(R.id.userNameView);
//trying to get comic sans from the tfa object
userName.setTypeface(tfa.cs);
}
}
答案 0 :(得分:0)
应该可以进行一些修改。在这种情况下,由于您需要使用getAssets()
,因此该类必须具有一个构造函数,该构造函数接受具有该方法的对象:Context
或Resources
。
以下是使用Context
的示例。
public class TypeFontAssets {
public static Typeface cs;
public static Typeface bh;
public static Typeface co;
public TypeFontAssets(Context context) {
cs = Typeface.createFromAsset(context.getAssets(),
"fonts/ComicSans.ttf");
bh = Typeface.createFromAsset(context.getAssets(),
"fonts/BradleyHand.ttf");
co = Typeface.createFromAsset(context.getAssets(),
"fonts/Courier.ttf");
}
}
然后在你的活动中,
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this class for ALL the fonts
TypeFaceAssets tfa = new TypeFaceAssets(this); // Activity has Context
TextView userName = (TextView)findViewById(R.id.userNameView);
//trying to get comic sans from the tfa object
userName.setTypeface(tfa.cs);
}
}