华为手机Edittext光标(cursor)颜色修改

华为手机的emui系统经常让人发出“可以可以,这很华为”的感叹

这两天在edittext部分也发生了这样的事情

正常edittext光标的颜色和宽度都说可以修改的,只需要通过xml中的 textCursorDrawable 属性就可以实现

但是到了华为手机上就直接会被系统默认一种很丑的光标风格覆盖

正常的方法都不管用,于是翻源码看到edittext的父类textview中的“mCursorDrawableRes”域是负责从xml文件中获取你通过 textCursorDrawable 设置的光标drawable

于是尝试简单粗暴地使用反射的方式对其进行修改,如下:

public class HWEditText extends EditText {

    public HWEditText(Context context) {
        this(context,null);
    }

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

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

    private void modifyCursorDrawable(Context context, AttributeSet attrs){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HWEditText);
        int drawable = a.getResourceId(R.styleable.HWEditText_textCursorDrawable,0);
        if(drawable != 0) {
            try {

                Field setCursor = TextView.class.getDeclaredField("mCursorDrawableRes");
                setCursor.setAccessible(true);
                setCursor.set(this, drawable);

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        a.recycle();
    }
}

 

run一下发现此方法奏效 

之后把这个类改成了适配增强类,同时给了一个自定义属性,可以在xml定义一个同名自定义属性对cursor进行修改,另外再把其他手机适配的几个小问题加进去了

posted @ 2016-08-17 13:59  赛艇队长  阅读(4525)  评论(6编辑  收藏  举报