華為手機的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進行修改,另外再把其他手機適配的幾個小問題加進去了