EditText修改光标和下划线颜色

来源:互联网 发布:阿里云搭建web服务器 编辑:程序博客网 时间:2024/04/29 19:32
1.更改下划线的颜色
   新建style
  <style name="UpdateUserEditText" parent="Theme.AppCompat.Light">
        <item name="colorControlNormal">@color/message_list_line</item>
        <item name="colorControlActivated">@color/message_list_line</item>
  </style>
 通过android:theme属性将此样式应用于您的EditText
 <EditText   android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="Hint text"  android:theme="@style/MyEditText"/> 


2.修改光标的颜色宽度
   一般手机可以通过android:textCursorDrawable=”@drawable/edit_cursor_color”属性直接改变光标颜色,android:textCursorDrawable=“@null”光标颜色与字体颜色一致;
   在华为手机等个别手机中要通过反射设置光标颜色才能生效
    第一步:新建drawable文件
    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:width="2dp"/>
    <solid android:color="@color/main_tab_home_selected"/>
</shape>
第二步在自定义属性
    <declare-styleable name="LineEditeText">
        <attr name="lineColorEt" format="color"/>
        <attr name="textCursorDrawable" format="reference"/>
    </declare-styleable>
第三步自定义EditText在构造方法中获取自定义属性
  TypedArray attrArrays = context.obtainStyledAttributes(attrs, R.styleable.LineEditeText);
 
        int lenght = attrArrays.getIndexCount();
        for(int i = 0 ; i < lenght; i ++){
            int index = attrArrays.getIndex(i);
            switch (index){ 
                case R.styleable.LineEditeText_textCursorDrawable:
                    try {
                        int drawable = attrArrays.getResourceId(R.styleable.LineEditeText_textCursorDrawable,0);
                        Field setCursor = TextView.class.getDeclaredField("mCursorDrawableRes");
                        setCursor.setAccessible(true);
                        setCursor.set(this, drawable);


                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
        attrArrays.recycle();
第四步应用到xml布局文件中
          <com.xfwy.ui.view.center.LineEditText 
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp120"
                    android:background="@null"     
                    app:textCursorDrawable="@drawable/edit_cursor_color"  />

原创粉丝点击