2012-01-09 17 views
43

¿Hay alguna manera de agregar fuentes personalizadas en Temas en Android?Agregar una fuente personalizada a Theme en Android

He leído Quick Tip: Customize Android Fonts, pero aquí tenemos que agregar programmetrically custom font a text.

TextView txt = (TextView) findViewById(R.id.custom_font); 
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf"); 
txt.setTypeface(font); 

Pero quiero establecer la fuente personalizada por estilo/tema.

Respuesta

-1

Espero que esto sea lo que quiso decir, pero si no lo es, debería ser una buena referencia para los demás de todos modos.

** Nota: Las fuentes se pueden encontrar PC/Disco local (C)/Windows/Fuentes **

Copiar la fuente que desea utilizar en la carpeta Fuentes arriba y pegarlo en un nuevo carpeta creada en la carpeta de activos en el Eclipse.

private void initTypeFace() 
    { 
     TypeFace tf = TypeFace.createFromAsset(getAsset(), 
         "Chantelli Antiqua.ttf"); 

     TextView txt = (TextView) findViewById(R.id.custom_font); 

     txt.setTypeface(tf); 
     example_button1.setTypeface(tf); 
     example_button2.setTypeface(tf); 
    } 
0

Creo que la respuesta a su pregunta será TextView personalizado con un parámetro XML adicional, que puede incluir en sus temas.

Puede analizar este valor en el constructor TextView (Context context, AttributeSet attrs) para inicializarlo. Consulte el enlace this, por ejemplo, para definir atributos personalizados para sus vistas e inicializarlos.

12

Creo que esto es un duplicado de this question y this one.

En mis actividades en tiempo de ejecución, utilizo algo como esto:

FontUtils.setCustomFont(findViewById(R.id.top_view), getAssets()); 

En XML:

 <TextView 
      android:id="@+id/my_label" 
      android:tag="condensed" 
      android:text="@string/label" 
      ... /> 

Así, teóricamente, puede crear estilo y utilizarlo junto con el código Fontutils/tiempo de ejecución. clase

<style name="roboto_condensed"> 
    <item name="android:tag">condensed,your-own-css-like-language-here</item> 
</style> 

Fontutils:

public class FontUtils { 
    private static Typeface normal; 

    private static Typeface bold; 

    private static Typeface condensed; 

    private static Typeface light; 

    private static void processsViewGroup(ViewGroup v, final int len) { 

    for (int i = 0; i < len; i++) { 
     final View c = v.getChildAt(i); 
     if (c instanceof TextView) { 
     setCustomFont((TextView) c); 
     } else if (c instanceof ViewGroup) { 
     setCustomFont((ViewGroup) c); 
     } 
    } 
    } 

    private static void setCustomFont(TextView c) { 
    Object tag = c.getTag(); 
    if (tag instanceof String) { 
     if (((String) tag).contains("bold")) { 
     c.setTypeface(bold); 
     return; 
     } 
     if (((String) tag).contains("condensed")) { 
     c.setTypeface(condensed); 
     return; 
     } 
     if (((String) tag).contains("light")) { 
     c.setTypeface(light); 
     return; 
     } 
    } 
    c.setTypeface(normal); 
    } 

    public static void setCustomFont(View topView, AssetManager assetsManager) { 
    if (normal == null || bold == null || condensed == null || light == null) { 
     normal = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Regular.ttf"); 
     bold = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Bold.ttf"); 
     condensed = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Condensed.ttf"); 
     light = Typeface.createFromAsset(assetsManager, "fonts/roboto/Roboto-Light.ttf"); 
    } 

    if (topView instanceof ViewGroup) { 
     setCustomFont((ViewGroup) topView); 
    } else if (topView instanceof TextView) { 
     setCustomFont((TextView) topView); 
    } 
    } 

    private static void setCustomFont(ViewGroup v) { 
    final int len = v.getChildCount(); 
    processsViewGroup(v, len); 
    } 
} 
3

Usted puede incluir el tipo de fuente personalizada en la carpeta de activos y retreive desde allí.

declarar las tipografías como:

Typeface helveticaBold; 
Typeface helveticaRegular; 

en onCreate() escribir el siguiente código:

helveticaBold = Typeface.createFromAsset(getAssets(), "helvetica_bold.ttf"); 
helveticaRegular = Typeface.createFromAsset(getAssets(), "helvetica_regular.ttf"); 

por último, establecer el tipo de letra del texto de Vista de Texto o EditarTexto como:

editText.setTypeface(helveticaRegular); 

eso es todo ...

+0

sí, pero no lo que está pidiendo – user1010160

4

Al usar mi CustomTextView, especifique un nombre de archivo de fuente en su carpeta assets directamente en su archivo de diseño XML.

Mi respuesta es here

19

Desafortunadamente, Android no proporciona la forma más rápida, fácil y limpia que busca cambiar la fuente para toda la aplicación. Pero recientemente investigué este asunto y creé algunas herramientas que te permiten cambiar la fuente sin ningún tipo de codificación (puedes hacerlo a través de xml, estilos e incluso apariencias de texto). Se basan en soluciones similares a las que se ven en las otras respuestas aquí, pero permiten mucha más flexibilidad. Puede leer todo al respecto en this blog, y ver el proyecto github here.

Aquí hay un ejemplo de cómo aplicar estas herramientas. Coloque todos sus archivos de fuentes en assets/fonts/. Luego, declare esas fuentes en un archivo xml (por ejemplo, res/xml/fonts.xml) y cargue este archivo temprano en su aplicación con TypefaceManager.initialize(this, R.xml.fonts); (por ejemplo, en la clase onCreate of your Application). El archivo XML es el siguiente:

<?xml version="1.0" encoding="utf-8"?> 
<familyset> 

    <!-- Some Font. Can be referenced with 'someFont' or 'aspergit' --> 
    <family> 
     <nameset> 
      <name>aspergit</name> 
      <name>someFont</name> 
     </nameset> 
     <fileset> 
      <file>Aspergit.ttf</file> 
      <file>Aspergit Bold.ttf</file> 
      <file>Aspergit Italic.ttf</file> 
      <file>Aspergit Bold Italic.ttf</file> 
     </fileset> 
    </family> 

    <!-- Another Font. Can be referenced with 'anotherFont' or 'bodoni' --> 
    <family> 
     <nameset> 
      <name>bodoni</name> 
      <name>anotherFont</name> 
     </nameset> 
     <fileset> 
      <file>BodoniFLF-Roman.ttf</file> 
      <file>BodoniFLF-Bold.ttf</file> 
     </fileset> 
    </family> 

</familyset> 

Ahora puede utilizar estas fuentes en su estilo o XML (siempre y cuando use las herramientas que he mencionado anteriormente), estableciendo el atributo flFont en el TextView encargo com.innovattic.font.FontTextView en su diseño xml . A continuación se puede ver cómo se puede aplicar una fuente a todos los textos en toda su aplicación, simplemente editando res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> 

    <!-- Application theme --> 
    <!-- Use a different parent if you don't want Holo Light --> 
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> 
     <item name="android:textViewStyle">@style/MyTextViewStyle</item> 
    </style> 

    <!-- Style to use for ALL text views (including FontTextView) --> 
    <!-- Use a different parent if you don't want Holo Light --> 
    <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView"> 
     <item name="android:textAppearance">@style/MyTextAppearance</item> 
    </style> 

    <!-- Text appearance to use for ALL text views (including FontTextView) --> 
    <!-- Use a different parent if you don't want Holo Light --> 
    <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo"> 
     <!-- Alternatively, reference this font with the name "aspergit" --> 
     <!-- Note that only our own TextView's will use the font attribute --> 
     <item name="flFont">someFont</item> 
     <item name="android:textStyle">bold|italic</item> 
    </style> 

    <!-- Alternative style, maybe for some other widget --> 
    <style name="StylishFont"> 
     <item name="flFont">anotherFont</item> 
     <item name="android:textStyle">normal</item> 
    </style> 

</resources> 

Con el acompañamiento res/layout/layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <!-- This text view is styled with the app theme --> 
    <com.innovattic.font.FontTextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="This uses my font in bold italic style" /> 

    <!-- This text view is styled here and overrides the app theme --> 
    <com.innovattic.font.FontTextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     app:flFont="anotherFont" 
     android:textStyle="normal" 
     android:text="This uses another font in normal style" /> 

    <!-- This text view is styled with a style and overrides the app theme --> 
    <com.innovattic.font.FontTextView 
     style="@style/StylishFont" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="This also uses another font in normal style" /> 

</LinearLayout> 

No se olvide de aplicar el tema en tu manifiesto de Android.

+0

gracias! EXCELENTE artículo .. –

+0

Como también está usando el código de Java, podemos hacerlo de una manera más simple –

+0

Esto realmente debería ser nativo en android – Zach

Cuestiones relacionadas