in application i can simply define attr.xml into values and use that into design layout. but i can not set this attributes programical into widgets, for example i have this attribute:
<declare-styleable name="ButtonTextStyle">
<attr name="font_button">
<enum name="consolas" value="0" />
<enum name="times" value="1" />
</attr>
</declare-styleable>
and i can use this attribute into xml by:
<com.sample.app.Widgets.ButtonTextStyle
android:id="#+id/btn_way_bill_click"
android:layout_width="fill_parent"
app:font_button="consolas">
now i'm define some Button programical into project and i want to use consolas font defined into font_button by:
button.setTextAppearance(context, R.attr.font_button);
but i get error for this code and i can not resolve problem, i'm define custom class extends from Button like with this:
public class ButtonTextStyle extends Button {
private Context mContext;
public ButtonTextStyle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init(attrs, defStyle);
}
public ButtonTextStyle(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init(attrs,-1);
}
public ButtonTextStyle(Context context) {
super(context);
mContext = context;
init(null,-1);
}
private void init(AttributeSet attrs,int defStyle) {
if (!isInEditMode()) {
TypedArray a = mContext.obtainStyledAttributes(attrs,R.styleable.ButtonTextStyle, defStyle, 0);
String str = a.getString(R.styleable.ButtonTextStyle_font_button);
switch (Integer.parseInt(str)) {
case 0:
str = "fonts/consolas.ttf";
break;
case 1:
str = "fonts/times.ttf";
break;
}
setTypeface(FontManager.getInstance(getContext()).loadFont(str));
}
}
}
PROBLEM:
Expected resource of type style
and i can not set for example enum to widgets like with set times font
HOW to set programical this custom class with attribute defined into attr.xml
UPDATED:
my class to add button is below method. i want to set font for it programically:
private void addButton(final CDialog owner, final Dialog dialog, final DialogButton dlgBtn) {
LinearLayout linearLayout = (LinearLayout) dialog.findViewById(R.id.tsw__layerButton);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 70);
//layoutParams.setMargins(11, 0, 8, 0);
Button button = new Button(context);
if (buttonTheme != -1) {
button.setBackgroundResource(buttonTheme);
}
button.setPadding(0,2,0,0);
button.setGravity(Gravity.CENTER);
button.setText(buttonMsg[dlgBtn.ordinal()]);
button.setTextSize(14);
button.setTextColor(G.context.getResources().getColor(R.color.white_text));
button.setWidth(dpToPx(buttonWidth));
//button.setHeight(dpToPx(32));
button.setLayoutParams(layoutParams);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
if (dialogListener != null) {
dialogListener.onCloseDialog(owner, dlgBtn);
}
}
});
linearLayout.addView(button);
}
Maybe this article will help you Android: Set Custom Attributes Programmatically and Via XML. Note, that there should be a style assigned to the R.attr.font_button attribute somewhere (for example in "AppTheme"). Because it's just an attribute, and it holds a reference to a value.
If you assigned a style in "AppTheme":
ButtonTextStyle button = (TextView) findViewById(R.id.btn_way_bill_click);
Resources.Theme themes = getTheme();
TypedValue storedValueInTheme = new TypedValue();
if (themes.resolveAttribute(R.attr.font_button, storedValueInTheme, true))
button.setTextAppearance(storedValueInTheme.data);
Or if you declared your own theme. It can be declared as follows
<resources>
<style name="ConsolasBtn" parent="#android:style/Widget">
<item name="font_button">consolas</item>
</style>
</resources>
Then you need to apply this theme to your button. Try
ButtonTextStyle button = (TextView) findViewById(R.id.btn_way_bill_click);
button.setTextAppearance(this, R.style.ConsolasBtn); // *this* refers to Context
Or try to pass R.style.ConsolasBtn to your constructor ButtonTextStyle(Context context, AttributeSet attrs, int defStyle) as the defStyle argument.
See also Styles and Themes, Resources.Theme, TypedValue, attrs.
I believe the proper way to achieve what you are trying to do is by first declaring an enum attribute...
<declare-styleable name="ButtonTextStyle">
<attr name="font_button" format="enum">
<enum name="consolas" value="0" />
<enum name="times" value="1" />
</attr>
</declare-styleable>
Only change from your original code is the format attribute. Then you can declare those custom style attributes as below...
<com.sample.app.Widgets.ButtonTextStyle
android:id="#+id/btn_way_bill_click"
android:layout_width="fill_parent"
app:font_button="consolas">
but, don't forget to declare the namespace(s) your sub-widget belongs to in the parent layout, otherwise you won't be able to reference the app alias
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.sample.app.Widgets">
and finally, your init method would look something like this...
private void init(AttributeSet attrs,int defStyle) {
if (!isInEditMode()) {
int i = -1;
TypedArray a = mContext.obtainStyledAttributes(attrs,R.styleable.ButtonTextStyle, defStyle, 0);
try{
a.getInt(R.styleable.ButtonTextStyle_font_button, -1);
}
finally{
a.recycle();
}
switch (i) {
case 0:
str = "fonts/consolas.ttf";
break;
case 1:
str = "fonts/times.ttf";
break;
}
setTypeface(FontManager.getInstance(getContext()).loadFont(str));
}
}
Setting the property programmatically
To set that property programmatically, you will need to expose a "setter" method that takes an integer value, then based on that value you can change the type face. To make things easier for consumers of your custom widget you can also define two constants in your class...
public static final int CONSOLAS = 0;
public static final int TIMES = 1;
then define the setter method...
public void setFontButton(int fontButton) {
if (fontButton != CONSOLAS && fontButton != TIMES) {
throw new IllegalArgumentException(
"fontButton must be one of CONSOLAS or TIMES");
}
//load the font and set it here, the same way you did in "init"
}
All you have to do is call that setter method and pass in one of the constants specified...
buttonTextStyle1.setFontButton(ButtonTextStyle.CONSOLAS);
Yet ANOTHER Update
Instead of doing...
Button button = new Button(context);
do...
ButtonTextStyle button = new ButtonTextStyle(context);
and make sure you import the correct class so it can be used in code...
import com.sample.app.Widgets.ButtonTextStyle;
Related
I want to add a custom Samsung font called SamsungOne to an Android app, I know you can link a font from online to put on a website, but how do you do this for an app, but using XML? Java is fine, but XML would be better. Can anyone help?
Add your .ttf downloaded from internet in app ⟶ src ⟶ main ⟶ assets.
Then you can use this code snippet to apply it to your textviews, edit texts etc.
TextView t = (TextView) findViewById(R.id.textView3);
Typeface typeface = Typeface.createFromAsset(getAssets(), "century_gothic.ttf");
// century_gothic.ttf is the name of your .ttf file stored in assets.
t.setTypeface(typeface);
You can just copy that font in asset folder and use it . With java :
typeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),
typefaceName);
To use it from xml you need to create a custom View(TextView or Edittext whatever you want).In attrs.xml you can define all types of type face and use the attribute to set Typeface. See the custom implementation of Edit text below:-
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
handleStyleable(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
handleStyleable(context, attrs);
}
private void handleStyleable(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomFont);
FONT_VAL font_val= FONT_VAL.NONE;
try {
for (FONT_VAL mode : FONT_VAL.values()) {
if (ta.getInt(R.styleable.CustomFont_typeface, 3) == mode.getId()) {
font_val = mode;
break;
}
}
if (font_val == FONT_VAL.MEDIUM_FONT) {
setTypeface(AppUtil.getTypeface(context, Constants.FontName.MEDIUM));
}else if(font_val== FONT_VAL.REGULAR_FONT){
setTypeface(AppUtil.getTypeface(context, Constants.FontName.REGULAR));
}else if(font_val== FONT_VAL.LIGHT_FONT){
setTypeface(AppUtil.getTypeface(context, Constants.FontName.LIGHT));
}else if(font_val== FONT_VAL.ITALIC){
setTypeface(AppUtil.getTypeface(context, Constants.FontName.ITALIC));
}else if(font_val== FONT_VAL.BOLD){
setTypeface(AppUtil.getTypeface(context, Constants.FontName.BOLD));
}
}catch (Exception e){
e.printStackTrace();
}
}
public enum FONT_VAL {
NONE(0),MEDIUM_FONT(1), REGULAR_FONT(2),LIGHT_FONT(3), ITALIC(4),BOLD(5);
private final int ID;
FONT_VAL(final int id) {
this.ID = id;
}
public int getId() {
return ID;
}
Define the custom attribute for each font in attrs.xml:-
<declare-styleable name="CustomFont">
<attr name="typeface" format="enum">
<enum name="medium_font" value="1" />
<enum name="regular_font" value="2" />
<enum name="light_font" value="3" />
<enum name="italic" value="4" />
<enum name="bold" value="5" />
</attr>
</declare-styleable>
Then you can directly use it in XMl :
<com.views.CustomTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/white"
app:typeface="bold" />
To set the font from external storage you need to do it at runtime only :
Typeface typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory(), "font.ttf"));
I need to add custom typeface for the listview items. And I have added the values to the list using using adapter like this
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), newList, R.layout.club_list2, from, to);
Here I want to set typeface for the textviews in club_list2 layout. How is it possible?
If you want set your custom typeface from xml you can do this
public class TypefaceTextView extends TextView {
private static Map<String, Typeface> mTypefaces;
public TypefaceTextView(final Context context) {
this(context, null);
}
public TypefaceTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypefaces == null) {
mTypefaces = new HashMap<String, Typeface>();
}
// prevent exception in Android Studio / ADT interface builder
if (this.isInEditMode()) {
return;
}
final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
if (array != null) {
final String typefaceAssetPath = array.getString(
R.styleable.TypefaceTextView_customTypeface);
if (typefaceAssetPath != null) {
Typeface typeface = null;
if (mTypefaces.containsKey(typefaceAssetPath)) {
typeface = mTypefaces.get(typefaceAssetPath);
} else {
AssetManager assets = context.getAssets();
typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
mTypefaces.put(typefaceAssetPath, typeface);
}
setTypeface(typeface);
}
array.recycle();
}
}
}
in xml.
<com.example.TypefaceTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp"
android:text="#string/hello_world"
geekui:customTypeface="fonts/yourfont.ttf" />
and your font should be in asset/fonts/ folder
create resource file inside values and set it as name attrs.xml
then copy past this there
<resources>
<declare-styleable name="TypefaceTextView">
<attr name="customTypeface" format="string" />
</declare-styleable>
</resources>
If you want them all to use the same one, use android:typeface in the xml. If you want themto use different ones, set it on the TextView in your getView function.
the default is not Arial. The default is Droid Sans.
change to a different built-in font
Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java(android).
Example
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/Arial.otf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf)
This question already has answers here:
Is it possible to set a custom font for entire of application?
(25 answers)
Closed 8 years ago.
i am working on implementation of custom font in android application..i want to use one custom font for entire application using styles.XML or may be another options is any.
There is no easy built-in way to do this in Android.
You might want to check out Calligraphy, an open source project that makes it easy to change the font for a whole app.
I had the same problem and I didn't find a way to do it with .xml files,
at end I inheritance TextView and EditText and apply the font by code
put the .otf files at assets/fonts library in your project
create a TextViewFont class that inheritance from TextView
public class TextViewFont extends TextView
{
private int mType = 0;
public TextViewFont(Context context)
{
this(context,null,0);
}
public TextViewFont(Context context, AttributeSet attrs)
{
this(context,attrs,0);
}
public TextViewFont(Context context, AttributeSet attrs, int defStyle)
{
super(context,attrs,defStyle);
init(context,attrs);
}
public void setType(int type){
this.mType= type;
Typeface tf;
switch (mType)
{
case 0:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-light.otf");
setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-regular.otf");
setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xxx-bold.otf");
setTypeface(tf);
break;
}
}
private void init(Context context, AttributeSet attrs )
{
if (attrs != null)
{
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.TextViewFont,
0, 0);
try
{
TypedValue tv = new TypedValue();
if (a.getValue(0, tv))
{
mType = (int)tv.data;
}
mType = a.getInteger(R.styleable.TextViewFont_fontType,0);
}
finally
{
a.recycle();
}
}
if (!isInEditMode())
{
Typeface tf;
switch (mType)
{
case 0:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-light.otf");
setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-regular.otf");
setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(context.getAssets(), "fonts/xxx-bold.otf");
setTypeface(tf);
break;
}
}
}
}
3.Using example inside xml layout file
in the header of the file you use the custom view add
xmlns:custom="http://schemas.android.com/apk/res-auto"
and add the custom class as any other view element
<xxxx.xxxx.xxxx.TextViewFont
android:id="#+id/xxxxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abcdEFGH 123"
android:textAppearance="#style/xxxxxxx"
custom:fontType="Regular" />
define the custom xml attributes vlaues/attrs.xml
<resources>
<declare-styleable name="TextViewFont">
<attr name="fontType" format="enum">
<enum name="Light" value="0"/>
<enum name="Regular" value="1"/>
<enum name="Bold" value="2"/>
</attr>
</declare-styleable>
</resources>
I am implementing my own custom DialogPreference subclass, like so:
public class MyCustomPreference extends DialogPreference
{
private static final String androidns = "http://schemas.android.com/apk/res/android";
private String mDialogMsg;
public MyCustomPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
mDialogMsg = attrs.getAttributeValue(androidns, "dialogMessage");
...
}
...
}
As you can see, I get the dialogMessage XML attribute and save it in the member variable mDialogMsg.
My problem is: my current code does not allow for the dialogMessage XML attribute to be specified as a string resource id in the XML.
In other words, this works:
android:dialogMessage="Hello world!"
But this doesn't:
android:dialogMessage="#string/hello_world"
If I specify it as a resource id in the XML, the resource id gets saved to mDialogMsg, not the string resource itself. Now, I know I could do:
context.getString(attrs.getAttributeValue(androidns, "dialogMessage"))
But then the user would not be able to enter a normal string in the XML (i.e. a non-resource id). I want to give the user the option of doing both. How do I do this?
int resId = attrs.getAttributeResourceValue(androidns, "dialogMessage", 0);
if(resId != 0){
mDialogMsg = getContext().getResources().getString(resId);
} else{
mDialogMsg = attrs.getAttributeValue(androidns, "dialogMessage");
}
I'm not sure if I completely understand your problem but if I do, string resources actually get saved as an integer value. I created the following function in an application to get the string value
public static String getToastString(int res, Context c)
{
String toast = "";
toast = c.getResources().getString(res);
return toast;
}
Then I can pass the resource and the context to get the value
1) Declare custom attribute:
<declare-styleable name="CustomItem">
<attr name="item_text" format="string"/>
</declare-styleable>
2) Obtain its value:
public CustomItem(Context context, AttributeSet attrs) {
super(context, attrs);
mTextView = (TextView) findViewById(R.id.text_view);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomItem);
try {
setText(a.getString(R.styleable.CustomItem_item_text));
} finally {
a.recycle();
}
}
public final void setText(String text) {
mTextView.setText(text);
}
public final void setText(#StringRes int resId) {
mTextView.setText(resId);
}
3) Use it in layout:
<com.example.CustomItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:item_text="#string/welcome_text"
/>
<com.example.CustomItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:item_text="Hello!"
/>
I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of Android.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NightRiderFont" parent="#android:style/TextAppearance">
<item name="android:typeface"> /***help need here***/ </item>
</style>
</resources>
However font is in "assets/fonts/". How can I access this font, so I can use that style as a theme to get rid of changing all TextViews by hand programatically.
As summary: How can I access 'a file from assets folder' in XML?
In my research, there is no way to add external font to the xml file. Only the 3 default font is available in xml
But you can use in java using this code.
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");
textfield.setTypeface(tf,Typeface.BOLD);
Update:
Now I find a way to do this by creating a custom class extending the TextView and use that in the xml file.
public class TextViewWithFont extends TextView {
private int defaultDimension = 0;
private int TYPE_BOLD = 1;
private int TYPE_ITALIC = 2;
private int FONT_ARIAL = 1;
private int FONT_OPEN_SANS = 2;
private int fontType;
private int fontName;
public TextViewWithFont(Context context) {
super(context);
init(null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.font, defStyle, 0);
fontName = a.getInt(R.styleable.font_name, defaultDimension);
fontType = a.getInt(R.styleable.font_type, defaultDimension);
a.recycle();
MyApplication application = (MyApplication ) getContext().getApplicationContext();
if (fontName == FONT_ARIAL) {
setFontType(application .getArialFont());
} else if (fontName == FONT_OPEN_SANS) {
setFontType(application .getOpenSans());
}
}
private void setFontType(Typeface font) {
if (fontType == TYPE_BOLD) {
setTypeface(font, Typeface.BOLD);
} else if (fontType == TYPE_ITALIC) {
setTypeface(font, Typeface.ITALIC);
} else {
setTypeface(font);
}
}
}
and in xml
<com.example.customwidgets.TextViewWithFont
font:name="Arial"
font:type="bold"
android:layout_width="wrap_content"
android:text="Hello world "
android:padding="5dp"
android:layout_height="wrap_content"/>
dont forget to add the schema in root of your xml
xmlns:font="http://schemas.android.com/apk/res-auto"
And create an attrs.xml file inside values directory, which is holding our custom attribues:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="font">
<attr name="type">
<enum name="bold" value="1"/>
<enum name="italic" value="2"/>
</attr>
<attr name="name">
<enum name="Arial" value="1"/>
<enum name="OpenSans" value="2"/>
</attr>
</declare-styleable>
</resources>
Update:
Found some performance issue when this custom view is used in
listview, that is because the font Object is creating every time the
view is loaded. Solution I found is to initialize the font in Application
Class and refer that font object by
MyApplication application = (MyApplication) getContext().getApplicationContext();
Application class will look like this
public class MyApplication extends Application {
private Typeface arialFont, openSans;
public void onCreate() {
super.onCreate();
arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL);
openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS);
}
public Typeface getArialFont() {
return arialFont;
}
public Typeface getOpenSans() {
return openSans;
}
}
Edit 2:
Finally fonts are supported by xml (also backwards compatible via support library): https://developer.android.com/preview/features/fonts-in-xml.html
Edit:
I now use the Calligraphy library . It is the easiest way for custom fonts.
What can you do:
Custom font in a TextView
Custom font in TextAppearance
Custom font in Styles
Custom font in Themes
FontSpannable to only apply font to a part of the text
I found another way to do this.
You have to make your own TextView using this tutorial
It is not that difficult and after this you can just use that TextView with your own font.
I don't know if anybody still watches this, but I thought it might help.
Uses this function if you are using single font.
public static void applyFont(final Context context, final View root, final String fontName) {
try {
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
for (int i = 0; i < viewGroup.getChildCount(); i++)
applyFont(context, viewGroup.getChildAt(i), fontName);
} else if (root instanceof TextView)
((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName));
} catch (Exception e) {
Log.e("ProjectName", String.format("Error occured when trying to apply %s font for %s view", fontName, root));
e.printStackTrace();
}
}
Soorya is right, but if you have to put the same font on many textViews, I recommend you to put that code inside a static method that return the Typeface wanted. It will reduce lines in your code. Or even better create a class that extends Application and make a GET method that return the Typeface. That method will be reachable from any Activity inside your application (without the need of using static variables or static methods).
Check this out with the help of this don't need to set custom font programmatically.
https://stackoverflow.com/a/27588966/4331353
fount change is very basic functionality in android which is mostly needed to each and every application.so every one want to change only once in application that reduce our development time so i would suggest you to see this link
FountChanger.class.
You Have just make Public calls And attached Method like this
public class TextViewFontType {
public Typeface typeface;
public void fontTextView(final TextView textView, final String fonttype) {
typeface = Typeface.createFromAsset(textView.getContext().getAssets(), fonttype);
textView.setTypeface(typeface);
}
have you use any where method TextView set font-family.
public class FontList {
public static final String gothicbNormal="fonts/gothicb.ttf";
public static final String gothicbBold="fonts/gothicb.ttf";
}
made FontList calss after you have just call methods any where with pass two parameter.
I took droid kid's answer and made it work with ANY font, just by typing the font filename directly into the XML:
layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" >
<!-- where font file is at "assets/fonts/arial.ttf" -->
<com.odbol.widgets.TextViewWithFont
...
custom:fontFilePath="fonts/arial.ttf" />
</RelativeLayout>
Fonts.java
public class Fonts {
// use Weak so fonts are freed from memory when you stop using them
private final static Map<String, Typeface> fonts = new WeakHashMap<>(5);
/***
* Returns a font at the given path within the assets directory.
*
* Caches fonts to save resources.
*
* #param context
* #param fontPath Path to a font file relative to the assets directory, e.g. "fonts/Arial.ttf"
* #return
*/
public synchronized static Typeface getFont(Context context, String fontPath) {
Typeface font = fonts.get(fontPath);
if (font == null) {
font = Typeface.createFromAsset(context.getAssets(), fontPath);
fonts.put(fontPath, font);
}
return font;
}
}
values/attrs.xml
<resources>
<declare-styleable name="TextViewWithFont">
<!-- a path to a font, relative to the assets directory -->
<attr name="fontFilePath" format="string" />
<attr name="type">
<enum name="bold" value="1"/>
<enum name="italic" value="2"/>
</attr>
</declare-styleable>
</resources>
TextViewWithFont.java
public class TextViewWithFont extends TextView {
private int defaultDimension = 0;
private int TYPE_BOLD = 1;
private int TYPE_ITALIC = 2;
private int fontType;
private int fontName;
public TextViewWithFont(Context context) {
super(context);
init(null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.TextViewWithFont, defStyle, 0);
String fontPath = a.getString(R.styleable.TextViewWithFont_fontFilePath);
fontType = a.getInt(R.styleable.TextViewWithFont_type, defaultDimension);
a.recycle();
if (fontPath != null) {
setFontType(Fonts.getFont(getContext(), fontPath));
}
}
private void setFontType(Typeface font) {
if (fontType == TYPE_BOLD) {
setTypeface(font, Typeface.BOLD);
} else if (fontType == TYPE_ITALIC) {
setTypeface(font, Typeface.ITALIC);
} else {
setTypeface(font);
}
}
}
hope use full to you:-
TextView text = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
text.setTypeface(font);
Instead of assets folder, you can put the .ttf file on fonts folder.
To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+.
Right click res folder, new -> Android resource directory-> select font -> Ok.
put your "myfont.ttf" file in newly created font folder.
On res/values/styles.xml
add,
<style name="customfontstyle" parent="#android:style/TextAppearance.Small">
<item name="android:fontFamily">#font/myfont</item>
</style>
On layout file add android:textAppearance="#style/customfontstyle",
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/customfontstyle"/>
Refer : https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
//accessing font file in code,
Typeface type = Typeface.createFromAsset(getResources().getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);//assign typeface to textview
//in assets folder->fonts(foldername)->arial.ttf(font file name)
You can use this library: https://github.com/InflationX/Calligraphy
You only have to add the font you want to use on your layout.
Like this:
<TextView
fontPath="fonts/verdana.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
1.Fisrt we can add assets folder> in that your font styles.ttfs in your app then
2.write access code for fonts in strings like :
<string name="fontregular">OpenSans-Light.ttf</string>
<string name="fontmedium">OpenSans-Regular.ttf</string>
3.Accessing some layout xml file textview code like this below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#string/fontregular"
android:textColor="#color/normalfont"
android:textSize="#dimen/textregular"/>
4.Add dimensions for font size :
<dimen name="textregular">14sp</dimen>
<dimen name="textheader">16sp</dimen>
<dimen name="smalltext">12sp</dimen>
<dimen name="littletext">10sp</dimen>
<dimen name="hightfont">18sp</dimen>
5.Add font color in colors :
<color name="normalfont">#666</color>
<color name="headerfont">#333</color>
<color name="aquablue">#4da8e3</color>
<color name="orange">#e96125</color>
6.Then apply changes it is easy process to change hole app.
Happy coding keep smile..
You can access your font file from assets folder to xml file.
android:fontFamily="fonts/roboto_regular.ttf"
fonts is the sub folder in assets folder.