2016-05-10 13 views
4

コードのXMLからフォントファミリ名attr名を取得したいとします。 は、たとえば、私は、カスタムのTextViewクラスを持っている:TextViewからfontFamily名を取得する方法は?

public class TextVieww extends TextView{ 

    public TextVieww(Context context) { 
     super(context); 
    } 
    public TextVieww(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 
    public TextVieww(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 
    public void init(Context mContext ,TextView view) { 
    } 
} 

はXML:

<com.typefacetest.TextVieww 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textSize="30sp" 
     android:textStyle="bold" 
     android:fontFamily="sans-serif-thin" 
     android:text="Hello World!" /> 

私はtextView.classから "サンセリフ・シン" を取得したいです。 これは可能ですか?どのようにこれを行うには?感謝の戻ります。まずsetTypeface(Typeface.SANS_SERIF)

+0

アセットフォルダに.ttfファイルを置くtextView.class&call XML上のそれ –

+0

私はちょうどそれを置き換えていない、フォントファミリの現在の名前をしたい – Anna

+0

textView.setTypeface(Typeface.create( "sans-serif-thin"、Typeface.NORMAL));これは好きですか? –

答えて

2

フォントファミリ名がプログラムで定義されている場合、XMLで定義されていると、コンパイル時に関連付けられたネイティブフォントファミリにマップされているため、醜いリフレクションなしに取り消せません。完全な答えのための上記の主張のための源を見つけなさい、タイプフェイスのためのドキュメンテーションは限られているようである)。

@Ashwiniのコメントで述べたように、assetsフォルダーの下でカスタムフォントを使用することができ、XMLファイルと.javaの両方でそれを見ることができます。

また、ネイティブフォントファミリを使用したい場合は、より単純で、少し面白くできます。 XMLで

:フォントファミリ名を格納するためのTextViewのタグフィールド:アンドロイドを使用RES /値/のstrings.xmlで

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    android:id='@+id/textView' 
    android:textSize="30sp" 
    android:textStyle="bold" 
    android:fontFamily="@string/myFontFamily" 
    android:tag="@string/myFontFamily" 
/> 

<resources> 
    ... 
    <string name="myFontFamily">sans-serif-thin</string> 
    ... 
</resources> 

次にあなたがアクセスすることができますandroid:tagフィールドを通じてフォントファミリ名:

TextView textView = (TextView) findViewById(R.id.textView); 
String fontFamily = String.valueOf(textView.getTag()); 
+1

の前に使ったフォントファミリの名前「Tag」それはそれを愛する素晴らしいアイデアです!ありがとう:) – Anna

2

http://developer.android.com/reference/android/widget/TextView.html#getTypeface()

TextView 、その後

public Typeface getTypeface() 

テキストが表示されている現在の書体とスタイル。

+0

いいえ、それは申し訳ありません...私はxmlで設定したフォントファミリをプログラム的に知りたいだけです。 フォントファミリの文字列名を取得し、新しい書体を設定しないようにしてください – Anna

+1

@Andr Typefaceオブジェクトからどのようにフォントファミリ名を取得しますか? – Sevle

+1

まさに私が知りたいことです。 – Anna

関連する問題