一溺蕉、需求背景:
項目開發(fā)中經(jīng)常遇到輸入框,有時候需要自定義光標(biāo)
二仿村、預(yù)期效果:
三、實現(xiàn)方式
1兴喂、xml格式
文件布局
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textCursorDrawable="@drawable/cursor_bg"/>
drawable資源蔼囊,用shape控制是一個長方形:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:width="3dp" />
<solid android:color="#FF2B87" />
</shape>
2、動態(tài)設(shè)置(適用于需要動態(tài)更改光標(biāo)樣式)
/**
* 反射設(shè)置光標(biāo)顏色 R.drawable.edittext_cursor
*
* @param edittextView
* @param drawable 資源文件
*/
public static void setCursorColor(EditText edittextView, int drawable) {
try {//修改光標(biāo)的顏色(反射)
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(edittextView, drawable);
} catch (Exception e) {
//Log.e(TAG,e);
}
}
四衣迷、特殊問題
1.魅族畏鼓,小米,設(shè)置hint為兩行時默認(rèn)光標(biāo)高度不一致問題
可以通過反射設(shè)置自定義的Drawable:
/**
* 特殊設(shè)置光標(biāo)
* @param topOffset 需要修正的上方距離
* @param bottomOffset 需要修正的下方距離
* @param view EditText
* */
public static void setTextCursorDrawable(int topOffset, int bottomOffset, EditText view) {
try {
Method method = TextView.class.getDeclaredMethod("createEditorIfNeeded");
method.setAccessible(true);
method.invoke(view);
Field field1 = TextView.class.getDeclaredField("mEditor");
Field field2 = Class.forName("android.widget.Editor").getDeclaredField("mCursorDrawable");
field1.setAccessible(true);
field2.setAccessible(true);
Object arr = field2.get(field1.get(view));
Array.set(arr, 0, new LineSpaceCursorDrawable(R.color.xxxxxx), 5), topOffset, bottomOffset));
Array.set(arr, 1, new LineSpaceCursorDrawable(R.color.xxxxxx), 5, topOffset, bottomOffset));
} catch (Exception ignored) {
//Log.e(TAG,ignored);
}
}
上面所用的自定義的LineSpaceCursorDrawable,控制Bounds實現(xiàn):
private static class LineSpaceCursorDrawable extends ShapeDrawable {
private int mTopOffset,mBottomOffset;
public LineSpaceCursorDrawable(int cursorColor,int cursorWidth,int topOffset, int bottomOffset) {
mTopOffset = topOffset;
mBottomOffset = bottomOffset;
setDither(false);
getPaint().setColor(cursorColor);
setIntrinsicWidth(cursorWidth);
}
//通過mTopOffset壶谒,mBottomOffset來控制drawable的上下坐標(biāo)
public void setBounds(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
super.setBounds(paramInt1, paramInt2+mTopOffset, paramInt3, paramInt4+mBottomOffset);
}
}
在此記錄一下云矫,加油ing~~