programing

텍스트 편집 커서 색상 설정

skycolor 2023. 6. 1. 22:36
반응형

텍스트 편집 커서 색상 설정

태블릿 프로젝트에서 안드로이드의 홀로 테마를 사용하는 문제가 발생했습니다.하지만 화면에 흰색 배경의 단편이 있습니다.는 를 추가합니다.EditText구성 요소입니다.홀로의 배경을 설정하여 테마를 오버라이드하려고 했습니다.테마 리소스에 불을 붙입니다.그러나 텍스트 커서(캐럿)는 흰색으로 유지되어 화면에 보이지 않습니다(텍스트 편집 필드에서 희미하게 볼 수 있습니다...).

편집 텍스트에서 더 어두운 커서 색을 사용하도록 하는 방법을 아는 사람이 있습니까?을 텍트편스집다타음설보로았정다니습해으스을일로 "@android:style/Widget.Holo.Light.EditText"긍정적인 결과가 없는

android:textCursorDrawable 다리탓으에 대한 .@null의 사용으로 이어져야 합니다.android:textColor커서 색으로 표시합니다.

"textCursorDrawable" 특성은 API 레벨 12 이상에서 사용할 수 있습니다.

배치 중

<EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textCursorDrawable="@drawable/color_cursor"
    />

그런 다음 drawable xml: color_cursor를 만듭니다.

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

텍스트 편집 속성에 흰색 커서가 있습니다.

마치 모든 답이 덤불 주위를 도는 것처럼 보입니다.

의 신의에서.EditText속성을 합니다.

android:textCursorDrawable="@drawable/black_cursor"

그리고 추첨 가능한 것을 추가합니다.black_cursor.xml다음과 같이 리소스로 이동합니다.

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

필요한 경우 이 방법을 사용하여 더 다양한 커서를 만들 수도 있습니다.

최신 커서 색상을 변경하는 새로운 방법이 있습니다.Appcompactv21
바꿔요 ㅠㅠㅠㅠㅠcolorAccent다음과 같은 스타일로:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->

    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#088FC9</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#088FC9</item>

    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <!-- THIS IS WHAT YOU'RE LOOKING FOR -->
    <item name="colorAccent">#0091BC</item> 
</style>

그런 다음 앱 테마 또는 활동에 이 스타일을 적용합니다.

업데이트: 이 방법은 API 21+에서만 작동합니다.
업데이트 2: 작동할 수 있는 최소 안드로이드 버전이 확실하지 않습니다.
Android 버전으로 테스트됨:

2.3.7 - didn't work
4.4.4 - worked
5.0 - worked
5.1 - worked

답을 찾았습니다 :)

테마의 텍스트 편집 스타일을 다음으로 설정했습니다.

<item name="android:editTextStyle">@style/myEditText</item>

그런 다음 다음 그림 그리기 도구를 사용하여 커서를 설정했습니다.

`

<style name="myEditText" parent="@android:style/Widget.Holo.Light.EditText">
    <item name="android:background">@android:drawable/editbox_background_normal</item>
    <item name="android:textCursorDrawable">@android:drawable/my_cursor_drawable</item>
    <item name="android:height">40sp</item>
</style>

`

안드로이드:textCursorDrawable이 여기서 핵심입니다.

설정이 필요한 모든 사용자를 위해EditText커서 색상을 동적으로 선택하면 아래에서 이를 달성하는 두 가지 방법을 찾을 수 있습니다.


먼저 그리기 가능한 커서를 만듭니다.

<?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>

커서 그리기 가능한 리소스 ID를 작성한 그리기 가능한 리소스(소스)로 설정합니다.

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

그리기 가능한 기본 커서의 색상만 변경하려면 다음 방법을 사용할 수 있습니다.

    public static void setTextCursorColor(TextView textView, @ColorInt int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            final Drawable drawable = textView.getTextCursorDrawable();
            drawable.setTint(color);
            textView.setTextCursorDrawable(drawable);
        } else try {
            Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            fCursorDrawableRes.setAccessible(true);
            int   mCursorDrawableRes = fCursorDrawableRes.getInt(textView);
            Field fEditor            = TextView.class.getDeclaredField("mEditor");
            fEditor.setAccessible(true);
            Object   editor          = fEditor.get(textView);
            Class<?> clazz           = editor.getClass();
            Field    fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
            fCursorDrawable.setAccessible(true);

            Drawable[] drawables = new Drawable[2];
            Resources  res       = textView.getContext().getResources();
            drawables[0] = res.getDrawable(mCursorDrawableRes);
            drawables[1] = res.getDrawable(mCursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            fCursorDrawable.set(editor, drawables);
        } catch (final Throwable throwable) {
            if (DEBUG) throw new RuntimeException("can't set text cursor color", throwable);
        }
    }

파티에 늦었지만,제 대답은 이렇습니다.

이것은 변화를 기대하지 않는 사람들을 위한 것입니다.colorAccent그들의 부모 테마에서, 하지만 바꾸고 싶어합니다.EditText속성!

이 답변은 변경 방법을 보여줍니다...

  1. 맨 아래 줄 색
  2. 커서 색
  3. 색상 이미지 의 커포사터(색자지이사용지미상)..........EditText활동 테마에 적용된 스타일을 사용합니다.

여기에 이미지 설명 입력

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hey" />

예:

<style name="AppTheme.EditText" parent="@style/Widget.AppCompat.EditText">
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">#8AFFFFFF</item>
    <item name="android:background">@drawable/edit_text_background</item> // background (bottom line at this case)
    <item name="android:textCursorDrawable">@color/white</item>  // Cursor
    <item name="android:textSelectHandle">@drawable/my_white_icon</item> // For pointer normal state and copy text state
    <item name="android:textSelectHandleLeft">@drawable/my_white_icon</item>
    <item name="android:textSelectHandleRight">@drawable/my_white_icon</item>
</style>

이제 그리기 가능한 항목을 만듭니다.edit_text_background 백그라운드에 리소스 xml을 추가합니다!원하는 대로 커스터마이징할 수 있습니다!

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="0dp"
        android:left="-3dp"   
        android:right="-3dp"
        android:top="-3dp">

        <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="@color/white"/>
        </shape>
    </item>
    </layer-list>

이제 활동 테마에서 이 스타일을 설정했습니다.

예:

. 이 정의를 합니다.editText그것에 대한 주제.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Your Theme data -->
    <item name="editTextStyle">@style/AppTheme.EditText</item> // inculude this
</style>
Edittext cursor color you want changes your color.
   <EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textCursorDrawable="@drawable/color_cursor"
    />

xml을 만듭니다: 그런을 drawable xml 듭니다만음.color_cursor

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

와우 저는 이 파티에 정말 늦었지만 17일 전에 활동을 했습니다. 답변에 사용 중인 안드로이드 버전을 게시하는 것을 고려해야 합니다. 현재 이 답변은 Android 2.1 이상에서 작동합니다. RES/VALUES/STYLES로 이동하고 아래 코드 라인을 추가하면 커서가 검은색이 됩니다.

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!--<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">-->
    <!-- Customize your theme here. -->
    <item name="colorControlActivated">@color/color_Black</item>
    <!--Sets COLOR for the Cursor in EditText  -->
</style>

RES/COLOR 폴더에 이 코드 라인이 필요합니다.

<color name="color_Black">#000000</color>

왜 이렇게 늦게 게시합니까?Android가 머리가 많은 괴물이 된 것에 대해 어떤 형태의 범주를 고려하는 것이 좋을 수도 있습니다!

나를 위해 AppTheme와 value colors.xml을 모두 수정했습니다.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorControlNormal">@color/yellow</item>
    <item name="colorAccent">@color/yellow</item>
</style>

여기 colors.xml이 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="yellow">#B7EC2A</color>
</resources>

@null에 대한 rodroid:textCursorDrawable 속성을 editText 스타일 안에 넣었습니다.이것을 사용해 보니 색이 변하지 않았습니다.

사용

android:textCursorDrawable="@color/white"
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item> -- change this one
</style>

styles.xml로 이동하여 색 액센트를 변경하면 편집 텍스트 상자의 커서에 영향을 줍니다.

유일하게 유효한 대답은 활동의 주제를 변경하는 것입니다.<item name="colorAccent">#000000</item>당신은 사면안됩다니하용을 하면 안 .android:textCursorDrawable@null커서 자체에만 관련이 있고 커서를 끌려면 커서 아래에 있는 핀에는 관련이 없기 때문입니다.주제 해결책이 가장 중요합니다.

여기서 @Jared Rummler의 프로그램 세트 CursorDrawableColor() 버전은 Android 9 Pie에서도 작동하도록 조정되었습니다.

@SuppressWarnings({"JavaReflectionMemberAccess", "deprecation"})
public static void setCursorDrawableColor(EditText editText, int color) {

    try {
        Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResField.setAccessible(true);
        int cursorDrawableRes = cursorDrawableResField.getInt(editText);
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editor = editorField.get(editText);
        Class<?> clazz = editor.getClass();
        Resources res = editText.getContext().getResources();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Field drawableForCursorField = clazz.getDeclaredField("mDrawableForCursor");
            drawableForCursorField.setAccessible(true);
            Drawable drawable = res.getDrawable(cursorDrawableRes);
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawableForCursorField.set(editor, drawable);
        } else {
            Field cursorDrawableField = clazz.getDeclaredField("mCursorDrawable");
            cursorDrawableField.setAccessible(true);
            Drawable[] drawables = new Drawable[2];
            drawables[0] = res.getDrawable(cursorDrawableRes);
            drawables[1] = res.getDrawable(cursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            cursorDrawableField.set(editor, drawables);
        }
    } catch (Throwable t) {
        Log.w(TAG, t);
    }
}

다음과 같이 미터법 테마로 할 수 있습니다.

<style name="Theme.App" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    ...
    <item name="android:colorControlNormal">#ff0000</item>
    <item name="android:colorControlActivated">#ff0000</item>
    <item name="android:colorControlHighlight">#ff0000</item>
    ...
</style>

확인란과 라디오 색상도 변경하려면 다음 줄을 추가합니다.

<item name="colorAccent">#ff0000</item>

Android API 21+에서 테스트했습니다.

고라하라고 .colorAccent안드로이드로.

res로 이동 -> values -> styles.xml 추가

<item name="colorAccent">#FFFFFF</item>

존재하지 않는 한

color.xml 편집

android:textCursorDrawable="@drawable/editcolor"

코드 in xml 트세 상드edittext

대화 상자에서 이 모든 기술을 시도하는 데 많은 시간을 보낸 후, 저는 마침내 주제를 텍스트 입력 레이아웃이 아닌 대화 상자 자체에 연결하는 아이디어를 얻었습니다.

<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorWhite</item>
    <item name="colorAccent">@color/colorPrimary</item>

</style>

작성 시 내부:

공개 클래스 myDialog 확장 대화 상자 {

private Activity activity;
private someVars;

public PopupFeedBack(Activity activity){
    super(activity, R.style.AppTheme_Dialog);
    setContentView(R.layout.myView);
    ....}}

건배 :)

스타일...에 정의된 현재 활동/조각/대화 상자에서 색상 액센트에 주의를 기울입니다.;) 커서 색상이 관련되어 있습니다.

또 다른 간단한 해결책은 프로젝트 폴더에서 res>values>colors.xml로 이동하여 원하는 색상으로 색상 액센트의 값을 편집하는 것입니다.

<color name="colorAccent">#000000</color>

위의 코드는 커서를 검은색으로 변경합니다.

그것보다 더 쉽습니다.

<style name="MyTextStyle">
    <item name="android:textCursorDrawable">#000000</item>
</style>

이는 ICS 및 그 이상에서 작동합니다.다른 버전에서는 테스트하지 않았습니다.

특정 색상을 원하시나요? AppCompatEdit를 사용해야 합니다.텍스트 후 역순 집합 null

나에게 효과가 있습니다.

<android.support.v7.widget.AppCompatEditText
    android:background="@null"
    android:textCursorDrawable="@color/cursorColor"/>

요점 참조

API 21 이상에서:

<com.google.android.material.textfield.TextInputLayout                
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:theme="@style/CursorColor">

// In colors.xml
<style name="CursorColor">
    <item name="colorPrimary">@color/black</item>
</style>>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#36f0ff</item>
    <item name="colorPrimaryDark">#007781</item>
    <item name="colorAccent">#000</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

색상 변경스타일에서 액센트.xm, 그것은 간단합니다.

스타일 및 구현을 사용하는 경우

색 컨트롤 활성화

해당 색상/흰색 이외의 값으로 대체합니다.

<style name="CustomTheme" parent="AppTheme">
    <item name="colorAccent">@color/yourColor</item>
</style>

스타일에서 추가한 다음 편집 텍스트에서 다음과 같이 테마를 설정합니다.

android:theme="@style/CustomTheme"

그게 다야!

레이아웃에서 아래 코드를 사용할 수 있습니다.

android:textCursorDrawable="@color/red"
        android:textColor="@color/black

언급URL : https://stackoverflow.com/questions/7238450/set-edittext-cursor-color

반응형