2017-07-09 2 views
-1

Je ne peux pas sembler pouvoir changer la police androïde standard à une autre dans mon application. J'écris mon application à Kotlin et j'utilise Anko pour l'exposer. J'ai essayé:Comment définir une police personnalisée pour l'application Android?

typeface = Typeface.create() 
typeface = Typface.createFromAsset(assets, "font/font_name") 
setTypeface(Typeface.createFromAsset(assets, "font/font_name")) 

Merci pour l'aide.

+1

Vous avez manqué l'extension de fichier. En plus de cela, Typeface.create ne supporte pas la mise en cache, donc c'est inutile si elle est répétée. Utilisez une bibliothèque: https://github.com/Drivemode/TypefaceHelper, https://github.com/chrisjenx/Calligraphy etc. –

+0

Merci beaucoup pour ça! –

Répondre

1

J'ai eu le même problème sur Android Studio 3.1 Canaries avec Kotlin

Voici la solution: pour police/lobster_regular.ttf fichier

var typeFace: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular) 

Exemple:

enter image description here

private var _customFontTextView: TextView? = null 
private var _typeFace:   Typeface? = null 

override fun onCreate(savedInstanceState: Bundle?) { 
    super.onCreate(savedInstanceState) 
    this.setContentView(R.layout.activity_main) 

    this._initializeResources() 
    this._initializeGUI() 
} 

private fun _initializeResources() { 
    this._customFontTextView = this.findViewById(R.id.custom_font_text_view) 
    this._typeFace   = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular) 
} 

private fun _initializeGUI() { 
    this._customFontTextView!!.setTypeface(this._typeFace, Typeface.NORMAL) 
} 

Vous pouvez également faire plus avec les polices téléchargeables, voici l'article de Google: https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts.html

1

Nous pouvons créer une classe pour textView personnalisé. par exemple nous avons besoin textview avec la police Roboto

class RobotoTextView(context: Context?, attrs: AttributeSet?) : AppCompatTextView(context, attrs) { 
    init { 
     val typeface = Typeface.createFromAsset(getContext().assets, "font/roboto.ttf") 
     if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB || 
       android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { 
      setTypeface(typeface) 
     } 
    } 
} 

alors nous pouvons l'utiliser sur chaque mise en page xml

<com.packagename.RobotoTextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello World"/> 
1

Essayez ceci, de this tutorial from SEGUN:

val myCustomFont : Typeface? = ResourcesCompat.getFont(this, R.font.my_font) 
myView.typeface = myCustomFont 

Note: vous » Vous devez avoir la police .ttf téléchargée dans votre projet pour ce faire - et pas seulement le .xml pour le downloa police de dable.