2016-04-25 3 views
0

Я хочу изменить шрифт моего полного приложения! Но я не знаю, как получить доступ к полному приложению. У меня есть способ получить доступ к тексту с помощью идентификатора, как я могу изменить код для доступа к всему приложению?Внешний внешний шрифт Android для полного приложения

public class ExternalFont extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    String fontPath = "fonts/FreeUniversal-Regular.ttf"; 
    TextView txtUniversal = (TextView) findViewById(R.id.universal); 
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath); 
    txtUniversal.setTypeface(tf); 
} 

}

ответ

0

Создайте свой собственный TextView с пользовательским стилем.

Пример:

public class YourTextView extends TextView { 

    public YourTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(); 
    } 

    public YourTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public YourTextView(Context context) { 
     super(context); 
     init(); 
    } 

    private void init() { 
     Typeface tf = Typeface.createFromAsset(context.getAssets(), 
      "fonts/yourfont.ttf"); 
     setTypeface(tf); 
    } 
} 

Вы можете использовать в вашем XML.

0

К сожалению, нет прямого способа, с помощью которого можно изменить шрифт всех текстовых элементов, которые вы используете в своем приложении, просто изменив шрифт по умолчанию.

Что вы можете сделать, это создать свой собственный TextView и установить на нем шрифт, как это предлагает #josedlujan. Но недостаток в этом подходе заключается в том, что каждый раз, когда будет создан объект TextView, будет создан новый объект Typeface, который крайне вреден для использования ОЗУ (объект Typeface обычно варьируется от 8-13 kb для шрифтов, таких как Roboto). Поэтому лучше кэшировать свой Typeface после его загрузки.

Шаг 1: Создание кэша Typeface для вашего приложения -

public enum Font { 

    // path to your font asset 
    Y("fonts/Roboto-Regular.ttf"); 

    public final String name; 
    private Typeface typeface; 

    Font(String s) { 
    name = s; 
    } 

    public Typeface getTypeface(Context context) { 

    if (typeface != null) return typeface; 
    try { 
     return typeface = Typeface.createFromAsset(context.getAssets(), name); 
    } catch (Exception e) { 
     return null; 
    } 
    } 

    public static Font fromName(String fontName) { 

    return Font.valueOf(fontName.toUpperCase()); 
    } 

Шаг 2: Определите свой собственный атрибут "customFont" в attrs.xml для CustomTextView

attrs.xml - 
<declare-styleable name="CustomFontTextView"> 
    <attr name="customFont"/> 
</declare-styleable> 


<com.packagename.CustomFontTextView 
      android:id="@+id/some_id" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      app:customFont="rl"/> 

Шаг 3: Создайте свой собственный TextView

public class CustomFontTextView extends TextView { 

public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    init(context, attrs); 
} 

public CustomFontTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(context, attrs); 
} 

public CustomFontTextView(Context context) { 
    super(context); 
    init(context, null); 
} 

private void init(Context context, AttributeSet attrs) { 

    if (attrs == null) { 
    return; 
    } 

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0 ,0); 
    String fontName = a.getString(R.styleable.CustomFontTextView_customFont); 

    String textStyle = attrs.getAttributeValue(styleScheme, styleAttribute); 

    if (fontName != null) { 
    Typeface typeface = Font.fromName(fontName).getTypeface(context); 
    if (textStyle != null) { 
     int style = Integer.decode(textStyle); 
     setTypeface(typeface, style); 
    } else { 
     setTypeface(typeface); 
    } 
    } 
    a.recycle(); 
} 
Смежные вопросы