继承特定的view完成自定义控件

自定义控件功能说明

  • 设置使用自定义的字体
  • 在EditText获得输入焦点的时候,下划线变为黄色,否则采用自己设置的灰色

代码如下

public class DinEditText extends AppCompatEditText implements View.OnFocusChangeListener {

    Typeface typeface;

    public DinEditText(Context context) {
        super(context);
        init(null);
    }

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

    void init(AttributeSet attrs) {
        setTypeface((ResourcesCompat.getFont(getContext(), R.font.dinot_bold)));

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            setOnFocusChangeListener(this);
            getBackground().setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(GrindrApplication.getGrindrApplication(), R.color.grindr_grey_3), PorterDuff.Mode.SRC_ATOP););
        }
    }

    public void onFocusChange(View v, boolean hasFocus) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            if (hasFocus) {
                // 关于setColorFilter这个方法大家可以自行百度 或者看我下面标记的一个网址链接 
                // setColorFilter的作用在这里是设置EditText的下划线输入时候的不同颜色
                getBackground().setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(GrindrApplication.getGrindrApplication(), R.color.grindr_goldenrod), PorterDuff.Mode.SRC_ATOP));
            } else {
                getBackground().setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(GrindrApplication.getGrindrApplication(), R.color.grindr_grey_3), PorterDuff.Mode.SRC_ATOP));
            }
        }
    }

    @Override
    public void setTypeface(Typeface typeface) {
        super.setTypeface(typeface);
    }

    @Override
    public Typeface getTypeface() {
        if (typeface == null) {
            return super.getTypeface();
        }
        return typeface;
    }
}

 @Override
    public void setText(CharSequence text, BufferType type) {
// 这里重写了setText() 方法 保证在使用自定义的字体  这里的代码就不贴了 下面有一个链接 可以参考这个链接 使用spannable来设计本文样式 使用自定义字体
        super.setText(FontManager.getDinSpannable(text, typeface), type);
    }

注意的地方

  • 关于colorFilter的解释
  • 关于spannable的使用介绍

你可能感兴趣的:(继承特定的view完成自定义控件)