美文网首页
android 设置输入框设置光标

android 设置输入框设置光标

作者: 无名指666 | 来源:发表于2021-01-10 21:15 被阅读0次

一、需求背景:

项目开发中经常遇到输入框,有时候需要自定义光标

二、预期效果:

三、实现方式

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、动态设置(适用于需要动态更改光标样式)

    /**
     * 反射设置光标颜色  R.drawable.edittext_cursor
     *
     * @param edittextView
     * @param drawable 资源文件
     */
    public static void setCursorColor(EditText edittextView, int drawable) {
        try {//修改光标的颜色(反射)
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            f.setAccessible(true);
            f.set(edittextView, drawable);
        } catch (Exception e) {
           //Log.e(TAG,e);
        }
    }

四、特殊问题

1.魅族,小米,设置hint为两行时默认光标高度不一致问题
可以通过反射设置自定义的Drawable:

     /**
     * 特殊设置光标
     * @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实现:

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的上下坐标
        public void setBounds(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
            super.setBounds(paramInt1, paramInt2+mTopOffset, paramInt3,  paramInt4+mBottomOffset);
        }
    }

在此记录一下,加油ing~~

相关文章

网友评论

      本文标题:android 设置输入框设置光标

      本文链接:https://www.haomeiwen.com/subject/eezkaktx.html