是否可以创建一个定义要在我的Activity中调用的对象的类?

时间:2014-08-08 00:29:41

标签: android android-resources android-assets android-typeface

我们只想说我想创建一个包含从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);
    }
}

1 个答案:

答案 0 :(得分:0)

应该可以进行一些修改。在这种情况下,由于您需要使用getAssets(),因此该类必须具有一个构造函数,该构造函数接受具有该方法的对象:ContextResources

以下是使用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);
    }
}