我正在尝试为自定义TextView类实现自定义属性。我按照Creating a View Class的方式跟着Android custom attribute for TextView来了解问题,如
还有更多。他们都是一样的,在这种情况下他们都没有帮助我!
所以这里有一些我的代码 attr (我添加了第一部分
<declare-styleable name="AvatarImageBehavior">
<attr name="finalYPosition" format="dimension"/>
<attr name="startXPosition" format="dimension"/>
<attr name="startToolbarPosition" format="dimension"/>
<attr name="startHeight" format="dimension"/>
<attr name="finalHeight" format="dimension"/>
</declare-styleable>
<declare-styleable name="CustomFont">
<attr name="toPersianNumbers" format="boolean" />
<attr name="cFontWeight" format="enum">
<enum name="thin" value="0"/>
<enum name="normal" value="1"/>
<enum name="bold" value="2"/>
</attr>
</declare-styleable>
XML
<com.sahab.omida.sahab.visualImprovements.AppCompact.TextViewPlus
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/load_sub_pickup_location"
custom:cFontWeight="bold"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
android:textColor="?titleColor"
android:textStyle="bold" />
**function**
public static int fontWeight(AttributeSet attrs, Context ctx, int defStyle){
TypedArray a = ctx.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomFont,
defStyle, 0);
int fontWeight;
try {
fontWeight = a.getInteger(R.styleable.CustomFont_cFontWeight,1);
Log.d("fontweight", "fontWeight: " + fontWeight);
} finally {
a.recycle();
}
return fontWeight;
}
and **one of my constructors**
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.ctx = context;
this.lang = SharedPreferenceHelper.getLang(context);
this.fontWeight = CustomFontsLoader.fontWeight(attrs,ctx,defStyle);
init();
}
以下是包含attrs的其他构造函数
this.fontWeight = CustomFontsLoader.fontWeight(attrs,ctx,0);
必须全部。它一定是我想念的小事。但无论我怎么检查,我都无法让它发挥作用。
PS。 TextView扩展了android.support.v7.widget.AppCompatTextView