如何为自定义视图类设置可绘制属性。

3

我正在尝试创建一个自定义视图 (editText) 类,它将帮助我设置 leftDrawable 并调整其大小:

我的问题是: 我试图设置我的 Drawable 但没有任何反应,奇怪的事实是我的 drawable 不为 null:

我的完整自定义 Edit Text 类

public class FontableEditText extends android.support.v7.widget.AppCompatEditText {

String TaFont;
float LD_Width, LD_Height;


public FontableEditText(Context context) {
    super(context);


}

public FontableEditText(Context context, AttributeSet attrs) {
    super(context, attrs);


    Drawable drawable;

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FontableEditText, 0, 0);
    try {

        TaFont = ta.getString(R.styleable.FontableEditText_ta_font);
        LD_Width = ta.getDimension(R.styleable.FontableEditText_ld_width, 0);
        LD_Height = ta.getDimension(R.styleable.FontableEditText_ld_height, 0);
        drawable = ta.getDrawable(R.styleable.FontableEditText_ld_drawable);


    } finally {
        ta.recycle();
    }

    setFont(TaFont);

    if (drawable != null) {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, (int) LD_Width, (int) LD_Height, true));
        this.setCompoundDrawables(d, null, null, null);
    }

}

void setFont(String FontName) {


    try {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + FontName);
        this.setTypeface(font);
    } catch (Exception e) {
        Log.v("Fontable View", e.getMessage(), new Throwable(e.getMessage()));
    }

}

public FontableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

}

我的 attr.xml

    <declare-styleable name="FontableEditText">
        <attr name="ta_font" format="string"/>
        <attr name="ld_drawable" format="reference"/>
        <attr name="ld_width" format="dimension" />
        <attr name="ld_height" format="dimension"/>
    </declare-styleable>

我的XML子元素

<com.tarlanahad.kitabstore.Views.FontableEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="18dp"
            android:layout_marginTop="40dp"
            android:background="@drawable/sign_in_edit_text_border"
            android:hint="you@yours.com"
            android:padding="10dp"
            android:textColor="@color/white"
            android:textColorHint="@color/white"
            android:textSize="17sp"
            app:ld_drawable="@drawable/sign_in_email_icon"
            app:ld_height="40dp"
            app:ld_width="40dp"
            app:ta_font="Lato-Light.ttf" />

你尝试过直接设置drawable吗?不需要通过Bitmaps的所有中间步骤。 - elmorabea
1个回答

2
尝试将格式从reference更改为integer 更改
 <attr name="ld_drawable" format="reference"/>

To

<attr name="ld_drawable" format="integer"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接