Подтвердить что ты не робот

Изменить цвет курсора edittext

Как изменить программный цвет EditText's курсора?

В Android 4.0 и выше цвет курсора белый. и если фон EditText также белый, он становится невидимым.

4b9b3361

Ответ 1

В свойствах EditText есть атрибут android:textCursorDrawable

Теперь установите для этого параметра значение @null,

android:textCursorDrawable="@null"

Итак, теперь ваш курсор EditText совпадает с вашим TextTolor EditText.

Ссылка из Установить цвет курсора EditText

Ответ 2

Я нашел способ исправить это. Это не самое лучшее решение, но оно работает.

К сожалению, я могу использовать только статический цвет для цвета курсора.

Сначала я определяю черный курсор в drawable

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

Далее я определяю образец EditText в макетах.

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textCursorDrawable="@drawable/blackpipe"
         >
    </EditText>

Когда я хочу создать EditText во время выполнения, я использую это:

AttributeSet editText30AttributeSet = null;
int res = getResources().getIdentifier("edit30", "layout", getPackageName());//edit30 is EditText layout
XmlPullParser parser = getResources().getXml(res);
int state=0;
do {
    try {
        state = parser.next();
    } catch (Exception e1) {
        e1.printStackTrace();
    }       
    if (state == XmlPullParser.START_TAG) {
        if (parser.getName().equals("EditText")) {
            editText30AttributeSet = Xml.asAttributeSet(parser);
            break;
        }
    }
} while(state != XmlPullParser.END_DOCUMENT);
EditText view = new EditText(getContext(),editText30AttributeSet);

Теперь у вас есть вид EditText с черным курсором. Может быть, кто-то может улучшить мое решение, чтобы курсор можно было изменить во время выполнения.

Ответ 3

Вот, что я думаю, лучшее решение, чем опубликовал @Adem.

Java:

try {
    // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(yourEditText, R.drawable.cursor);
} catch (Exception ignored) {
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ff000000" />

    <size android:width="1dp" />

</shape>

Ответ 4

Как насчет styles.xml с помощью AppCompat-v7?

<item name="colorControlNormal">@color/accentColor</item>
<item name="colorControlActivated">@color/accentColor</item>
<item name="colorControlHighlight">@color/accentColor</item>

Работает для меня (этот пример упрощен).

Ответ 5

улучшается ответ джареда Раммлера

Java:

try {
    // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(yourEditText, R.drawable.cursor);
} catch (Exception ignored) {
}

создайте файл custom_cursor.xml в папке res/drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ff000000" />

    <size android:width="1dp" />
</shape>

XML:

<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textCursorDrawable="@drawable/custom_cursor"
     >
</EditText>

Ответ 6

Вы можете установить атрибут android:textCursorDrawable на @null, что приведет к использованию android:textColor в качестве цвета курсора.

Атрибут textCursorDrawable доступен в уровне API 12 и выше...

Спасибо...

Ответ 7

Итак, здесь окончательная версия - не нуждается в XML и работает как @null, но программно:

try {
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set((TextView)yourEditText, 0);
} catch (Exception ignored) {
}

Единственная проблема заключается в том, что он может перестать работать в один прекрасный день с новой версией Android.

PS Я протестировал его на 4.1.2 до 5.1.

Ответ 8

Установить через AppTheme

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. -->
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:spinnerStyle">@style/spinner_style</item>
    <!--Add This-->
    <item name="editTextStyle">@style/EdittextStyle</item>
    <item name="android:dropDownListViewStyle">@style/SpinnerStyle</item>
</style>

<!--New EditText Style-->
<style name="EdittextStyle" parent="Widget.AppCompat.EditText">
    <item name="android:background">?attr/editTextBackground</item>
    <item name="android:textColor">?attr/editTextColor</item>
    <item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
    <!--<item name="android:textCursorDrawable">@drawable/abc_text_cursor_material</item>-->
    <item name="colorControlNormal">@color/colorAccent</item>
    <item name="colorControlActivated">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorAccent</item>

</style>

Ответ 9

использовать вы можете использовать код ниже

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="@color/grey"
    >
    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="input you name"
        android:padding="20dp"
        android:textColor="@color/black"
        android:textCursorDrawable="@null"
        />
    <EditText
        android:id="@+id/et_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input your age"
        android:padding="20dp"
        android:textCursorDrawable="@color/red"
        android:textColor="@color/black"
        />
</LinearLayout>

Референция от: изменить цвет курсора редактирования текста на андроид