Android 从自定义小部件构造函数读取基类xml属性?

Android 从自定义小部件构造函数读取基类xml属性?,android,Android,我有一个从标准库小部件派生的类,如何在构造函数中读取基类的一个xml属性?例如,我如何获得下面的“android:layout_height”值 class MyTextView extends TextView { public MyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr,

我有一个从标准库小部件派生的类,如何在构造函数中读取基类的一个xml属性?例如,我如何获得下面的“android:layout_height”值

class MyTextView extends TextView {

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

        int layoutHeightParamFromXmlAttributes = ?;
    }
}
我对以这种方式阅读其他“android:x”属性感兴趣,这只是一个例子


谢谢

您可以尝试以下方法:

在小部件构造函数中。 如果获得自定义属性,请尝试此操作

    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"/>


希望这个解释能对您有所帮助。:)

您可以尝试以下方法:

在小部件构造函数中。 如果获得自定义属性,请尝试此操作

    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"/>

希望这个解释能对您有所帮助。:)