Extending a EditText in Android. What am I doing wrong?

最后都变了- 提交于 2019-11-30 18:05:51

You will need to implement these constructors:

public class TestEditText extends EditText {
    public TestEditText(Context context) {
        super(context);
    }

    public TestEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

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

for example try to do the following :

public TestEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    Log.i("attribute name at index 0", attrs.getAttributeName(0));
}

you will get the following in your logcat :

attribute name at index 0 = id 

so to deliver these XML attributes to the Super class (EditText) you have to override these constructors.

Hope that Helps.

You have to add this constructor for creating any custom View.

public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
.....
}

instead of

public MyEditText(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }  
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;




/**
 * Created by rohann on 14/07/2016.
 */
public class LightEditText extends android.widget.EditText{

    public LightEditText(Context context) {
        super(context);
        setFont();

    }

    public LightEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFont();
    }

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

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public LightEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setFont();
    }

    /**
     * This method is used to set the given font to the TextView.
     */
    private void setFont() {
        Typeface typeface = TypefaceCache.get(getContext().getAssets(), "fonts/Roboto-Light.ttf");
        setTypeface(typeface);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!