2013-04-02 8 views
8

私はカスタムTextViewクラスMTextViewを作成しています。コンストラクタ内では、スタイルが太字に設定されているかどうかに応じて異なる書体を設定できるように、textviewのstyle attribの値を知りたいと思います。しかし、getStyle()関数はありませんか?何をすべきか?TextViewのスタイル属性を取得する方法

public class MTextView extends TextView{ 

    public MTextView(Context context, AttributeSet attrs, int defStyle) { 
      super(context, attrs, defStyle); 
      if(style.equals(TypeFace.bold)) //how to get style? 
       setTypeface(Typeface.createFromAsset(getContext().getAssets(),"rc.ttf")); 
    } 



    } 

答えて

25

TextViewのgetTypeface()インスタンスメソッドからtextStyleを取得できます。

int style = getTypeface().getStyle(); 

何TEXTSTYLEは、getTypeface()はnullを返すことができる(すなわち、あなたが通常のTEXTSTYLEをサポートしたい)が指定されていない場合。

nullでない場合、textStyleが暗黙的にnormalに設定されていると仮定するのが最善です。このコード

+0

は答えとして、それをマーク。 –

+0

男は明らかにスタイルを取得したいが、デフォルトのタイプフェイスからではなく、ttfファイルから作成します。答えとしてマークするべきではありません... – Borzh

+0

誰かが最終的に働く答え – Till

1

用途:

if (attrs != null) { 
     try { 
      int style = attrs.getAttributeIntValue(
       "http://schemas.android.com/apk/res/android", 
       "textStyle", 
       Typeface.NORMAL); 

      setTypeface(Typeface.createFromAsset(
          getContext().getAssets(), 
          "rc.ttf"), 
         style); 
     } 
     catch (Exception e) { 
      Log.e(TAG, e.getMessage()); 
     } 
    } 
関連する問題