titulo studio programacion personalizar móviles fuente desarrollo curso cambiar barra aplicaciones android fonts textview typeface

studio - manual de programacion android pdf



¿Establecer fuente para todas las textViews en actividad? (6)

ejemplo de una forma más "genérica" ​​con el uso de la reflexión:

** está presentando una idea de participación del método de los niños del grupo de visualización setTextSize (int, float) pero puede adoptarlo como en el caso de su pregunta a setTypeFace ()

/** * change text size of view group children for given class * @param v - view group ( for example Layout/widget) * @param clazz - class to override ( for example EditText, TextView ) * @param newSize - new font size */ public static void overrideTextSize(final View v, Class<?> clazz, float newSize) { try { if (v instanceof ViewGroup) { ViewGroup vg = (ViewGroup) v; for (int i = 0; i < vg.getChildCount(); i++) { View child = vg.getChildAt(i); overrideTextSize(child, clazz, newSize); } } else if (clazz.isAssignableFrom(v.getClass())) { /** create array for params */ Class<?>[] paramTypes = new Class[2]; /** set param array */ paramTypes[0] = int.class; // unit paramTypes[1] = float.class; // size /** get method for given name and parameters list */ Method method = v.getClass().getMethod("setTextSize",paramTypes); /** create array for arguments */ Object arglist[] = new Object[2]; /** set arguments array */ arglist[0] = TypedValue.COMPLEX_UNIT_SP; arglist[1] = newSize; /** invoke method with arguments */ method.invoke(v,arglist); } } catch (Exception e) { e.printStackTrace(); } }

PRECAUCIÓN:

usando la reflexión debería ser muy cuidadoso. Clase de reflexión es muy " excepcional "

  • por ejemplo, debe verificar la presencia de anotaciones para evitar diferentes tipos de problemas. En el caso del método SetTextSize (), es conveniente comprobar las anotaciones android.view.RemotableViewMethod

¿Es posible establecer la fuente para todos los TextViews en una actividad? Puedo establecer la fuente para un solo textView usando:

TextView tv=(TextView)findViewById(R.id.textView1); Typeface face=Typeface.createFromAsset(getAssets(), "font.ttf"); tv.setTypeface(face);

Pero me gustaría cambiar todas las textViews a la vez, en lugar de configurarla manualmente para cada textView, cualquier información sería apreciada.


El de mi colección personal:

private void setFontForContainer(ViewGroup contentLayout) { for (int i=0; i < contentLayout.getChildCount(); i++) { View view = contentLayout.getChildAt(i); if (view instanceof TextView) ((TextView)view).setTypeface(yourFont); else if (view instanceof ViewGroup) setFontForContainer((ViewGroup) view); } }


Extendiendo la respuesta de Agarwal ... puede configurar regular, negrita, cursiva, etc. cambiando el estilo de su TextView.

import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; public class TextViewAsap extends TextView { public TextViewAsap(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public TextViewAsap(Context context, AttributeSet attrs) { super(context, attrs); init(); } public TextViewAsap(Context context) { super(context); init(); } private void init() { if (!isInEditMode()) { Typeface tf = Typeface.DEFAULT; switch (getTypeface().getStyle()) { case Typeface.BOLD: tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Bold.ttf"); break; case Typeface.ITALIC: tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf"); break; case Typeface.BOLD_ITALIC: tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf"); break; default: tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Regular.ttf"); break; } setTypeface(tf); } } }

Puede crear su carpeta de Activos de esta manera:

Y su carpeta de Activos debería verse así:

Finalmente su TextView en xml debería ser una vista de tipo TextViewAsap. Ahora puede usar cualquier estilo que haya codificado ...

<com.example.project.TextViewAsap android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Example Text" android:textStyle="bold"/>


Si está buscando una solución programática más general, creé una clase estática que se puede usar para establecer el tipo de letra de una vista completa (UI de actividad). Tenga en cuenta que estoy trabajando con Mono (C #) pero puede implementarlo fácilmente usando Java.

Puede pasarle a esta clase un diseño o una vista específica que desee personalizar. Si quieres ser súper eficiente, puedes implementarlo usando el patrón Singleton.

public static class AndroidTypefaceUtility { static AndroidTypefaceUtility() { } //Refer to the code block beneath this one, to see how to create a typeface. public static void SetTypefaceOfView(View view, Typeface customTypeface) { if (customTypeface != null && view != null) { try { if (view is TextView) (view as TextView).Typeface = customTypeface; else if (view is Button) (view as Button).Typeface = customTypeface; else if (view is EditText) (view as EditText).Typeface = customTypeface; else if (view is ViewGroup) SetTypefaceOfViewGroup((view as ViewGroup), customTypeface); else Console.Error.WriteLine("AndroidTypefaceUtility: {0} is type of {1} and does not have a typeface property", view.Id, typeof(View)); } catch (Exception ex) { Console.Error.WriteLine("AndroidTypefaceUtility threw:/n{0}/n{1}", ex.GetType(), ex.StackTrace); throw ex; } } else { Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / view parameter should not be null"); } } public static void SetTypefaceOfViewGroup(ViewGroup layout, Typeface customTypeface) { if (customTypeface != null && layout != null) { for (int i = 0; i < layout.ChildCount; i++) { SetTypefaceOfView(layout.GetChildAt(i), customTypeface); } } else { Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / layout parameter should not be null"); } } }

En su actividad, deberá crear un objeto Typeface. Creo el mío en OnCreate () usando un archivo .ttf colocado en mi directorio de Recursos / Activos. Asegúrese de que el archivo esté marcado como un elemento de Android en sus ''propiedades.

protected override void OnCreate(Bundle bundle) { ... LinearLayout rootLayout = (LinearLayout)FindViewById<LinearLayout>(Resource.Id.signInView_LinearLayout); Typeface allerTypeface = Typeface.CreateFromAsset(base.Assets,"Aller_Rg.ttf"); AndroidTypefaceUtility.SetTypefaceOfViewGroup(rootLayout, allerTypeface); }


Solution1 :: Simplemente llame a estos métodos pasando la vista principal como argumento.

private void overrideFonts(final Context context, final View v) { try { if (v instanceof ViewGroup) { ViewGroup vg = (ViewGroup) v; for (int i = 0; i < vg.getChildCount(); i++) { View child = vg.getChildAt(i); overrideFonts(context, child); } } else if (v instanceof TextView ) { ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf")); } } catch (Exception e) { } }

Solution2 :: puede subclasificar la clase TextView con su fuente personalizada y usarla en lugar de textview.

public class MyTextView extends TextView { public MyTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyTextView(Context context) { super(context); init(); } private void init() { if (!isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf"); setTypeface(tf); } } }


Mejores respuestas

1. Establecer fuente personalizada para un textView

Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "Fonts/FontName.ttf"); textView.setTypeface (typeface);

2. Establecer fuente personalizada para todas las textViews

Crea una JavaClass como a continuación

public class CustomFont extends android.support.v7.widget.AppCompatTextView { public CustomFont(Context context) { super(context); init(); } public CustomFont(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CustomFont(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/FontName.ttf"); setTypeface(tf); } }

Y en tu página xml

<packageName.javaClassName> ... />

=>

<com.mahdi.hossaini.app1.CustomFont android:id="@+id/TextView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="KEEP IT SIMPLE" android:textAlignment="center" />