1. 程式人生 > >android 程式碼+xml 設定游標顏色

android 程式碼+xml 設定游標顏色

先說在Java程式碼設定:

1. 在此目錄建立:src/drawable/cursor_color.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <solid android:color="#a8a8a8"/>
    <size android:width="1dp"/>
</shape>

2. 用反射獲取TextView的變數:mCursorDrawableRes

try{
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(editText, R.drawable.cursor_color);
} catch (Exception ignored) {
}

這是一個封裝了共有方法,同樣也是在程式碼中設定游標顏色,你可以直接拿去使用:

/**
 * 程式碼設定游標顏色
*
 * @param editText 你使用的EditText
 * @param color    游標顏色
*/
public static void 
setCursorDrawableColor(EditText editText, int color) { try { Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");//獲取這個欄位 fCursorDrawableRes.setAccessible(true);//代表這個欄位、方法等等可以被訪問 int mCursorDrawableRes = fCursorDrawableRes.getInt(editText); Field fEditor = TextView.class
.getDeclaredField("mEditor"); fEditor.setAccessible(true); Object editor = fEditor.get(editText); Class<?> clazz = editor.getClass(); Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable"); fCursorDrawable.setAccessible(true); Drawable[] drawables = new Drawable[2]; drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes); drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes); drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);//SRC_IN 上下層都顯示。下層居上顯示。 drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN); fCursorDrawable.set(editor, drawables); } catch (Throwable ignored) { } }

mxl設定游標顏色:

EditText有一個屬性:android:textCursorDrawable,這個屬性是用來控制游標顏色的
android:textCursorDrawable="@null","@null"作用是讓游標顏色和text color一樣

謝謝此文章:

http://stackoverflow.com/questions/7238450/set-edittext-cursor-color