【问题标题】:Is it possible to create a Class that defines object to be called in my Activity?是否可以创建一个定义要在我的活动中调用的对象的类?
【发布时间】:2014-08-08 00:29:40
【问题描述】:

假设我想创建一个类来保存我从资产文件夹中获取的所有字体,这可能吗?

如果不导入android.app.activity,我就无法访问getAssets()

实用类

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);
    }
}

【问题讨论】:

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


    【解决方案1】:

    应该可以进行一些修改。在这种情况下,由于您需要使用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);
        }
    }
    

    【讨论】:

    • 完美,正是我所需要的。当然,我需要传递一个上下文才能访问当前项目的 getAssets() 。我非常接近。谢谢[链接]Andrew.T.You.Are.Mighty.aninote.com
    猜你喜欢
    • 2020-11-08
    • 2021-08-18
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多