2017-11-28 5 views
1

標準のライブラリウィジェットから派生したクラスがありますが、どのようにしてコンストラクタの基本クラスのxml属性を読み込むことができますか?例えば、私は「アンドロイド:layout_height」の値を取得する方法を次のように?:カスタムウィジェットコンストラクタから基本クラスxml属性を読み込みますか?

class MyTextView extends TextView { 

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 

     int layoutHeightParamFromXmlAttributes = ?; 
    } 
} 

私は他の読書に興味がある「アンドロイドを:x」は、このように属性、これは単なる一例です。

ウィジェットコンストラクタで:

おかげ

答えて

0

あなたはこのような何かを試すことができます。 カスタム属性を取得した場合は、これを試してください。

if (attrs != null) { 
       TypedArray attributeArray = context.obtainStyledAttributes(attrs,R.styleable.CustomTextView); 
       //for font 
       String fontName = attributeArray.getString(R.styleable.CustomTextView_font_name); 
} 

そして、あなたは、高さと幅などのデフォルトプロパティを取得する場合は、この試してみてください。

int width=attributeArray.getLayoutDimension(0,ViewGroup.LayoutParams.WRAP_CONTENT); 
int height = attributeArray.getLayoutDimension(1,ViewGroup.LayoutParams.WRAP_CONTENT);//index is based on your xml file 

この追加レイアウトファイルでattrs.xmlファイルに

<declare-styleable name="CustomTextView"> 
    <attr name="font_name" format="string" /> 
</declare-styleable> 

をスタイルを定義します。

<com.package.CustomTextView 
       android:id="@+id/customFTextView" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       app:font_name="OpenSans-Regular.ttf" 
       android:gravity="center"/> 

この説明があなたに役立つことを願っています。 :)

関連する問題