2011-12-07 12 views
4

のTextView(またはそのサブクラス)のカスタムフォント渡すためにどのような方法があります。このXMLからカスタムTrueTypeフォントのみが

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/CustomFont.ttf"); 
+0

いや、私はそうは思わ:( – ingsaurabh

+0

をなし、カスタムフォントを使用したい場合、あなたはそのためのJavaコードを記述するために持っていけません。 – anddev

答えて

5

のような任意のJavaコードを提供せずにのみ、XMLを使用してそれを行うことはできません純粋にXMLからですが、というカスタムビューを作成し、XMLから参照してください。この方法でコードを一度書くだけで、さまざまなレイアウトでリサイクルすることができます。例えば

、クラスFontTextView宣言:

package com.example; 

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class FontTextView extends TextView { 

    /** 
    * Note that when generating the class from code, you will need 
    * to call setCustomFont() manually. 
    */ 
    public FontTextView(Context context) { 
     super(context); 
    } 

    public FontTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setCustomFont(this, attrs); 
    } 

    public FontTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setCustomFont(this, attrs); 
    } 

    private void setCustomFont(Context context, AttributeSet attrs) { 
     if (isInEditMode()) { 
      // Ignore if within Eclipse 
      return; 
     } 
     String font = "myDefaultFont.ttf"; 
     if (attrs != null) { 
      // Look up any layout-defined attributes 
      TypedArray a = obtainStyledAttributes(attrs, 
        R.styleable.FontTextView); 
      for (int i = 0; i < a.getIndexCount(); i++) { 
       int attr = a.getIndex(i); 
       switch (attr) { 
       case R.styleable.FontTextView_customFont: 
        font = a.getString(attr, 0); 
        break; 
       } 
      } 
      a.recycle(); 
     } 
     Typeface tf = null; 
     try { 
      tf = Typeface.createFromAsset(getAssets(), font); 
     } catch (Exception e) { 
      Log.e("Could not get typeface: " + e.getMessage()); 
     } 
     setTypeface(tf); 
    } 

} 

res/values/attrs.xmlで属性を定義します。

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

    <declare-styleable name="FontTextView"> 
     <attr name="customFont" format="string" /> 
    </declare-styleable> 

</resources> 

は、レイアウトで使用してください:

  1. は、名前空間を宣言します。

    xmlns:custom="http://schemas.android.com/apk/res/com.example" 
    
  2. FontTextViewを使用します。

    <com.example.FontTextView 
        android:id="@+id/introduction" 
        customFont="myCustomFont.ttf" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Hello world!" /> 
    
+0

申し訳ありませんが、ButtonやCheckedTextView、CompountButtonなどを使用したい場合はどうすればいいですか?これは良い解決法ではありません:-( –

+2

'setCustomFont()'を静的コンテキストに一般化し、XMLコンストラクタを常に使用している場合は、ビュー要素ごとに1つのコンストラクタを定義する必要があります。私が拡張したいと思っていたコントロールが5つしかないことが判明しました。また、ビューやレイアウトの周りに余分なコードを書く必要がないので、最適な解決策であることがわかりました。 –

+0

@s_idこれは、新しいFontTextViewオブジェクトを作成するたびにタイプフェイスを読み込む必要がないように静的キャッシングを追加します。 – styler1972

関連する問題