Issue
Let's just say I want to create a class that holds all my fonts taken from the assets folder, is it possible?
It's not letting me access the getAssets()
without importing android.app.activity
.
Utility Class
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");
}
Main Activity
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);
}
}
Solution
It should be possible with some modifications. In this case, since you need to use getAssets()
, the class must have a constructor which accepts an object which has that method: Context
or Resources
.
Here is an example using 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");
}
}
Then in your activity,
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);
}
}
Answered By - Andrew T.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.