programing

Android에서 TextView 범위 색상 설정

itmemos 2023. 9. 24. 12:23
반응형

Android에서 TextView 범위 색상 설정

TextView에서 텍스트 스팬만의 색상을 설정할 수 있습니까?

저는 글의 일부분이 파란색인 트위터 앱과 비슷한 것을 하고 싶습니다.아래 이미지 참조:

alt text
(출처: twimg.com )

또 없을 입니다. 입니다.TextView두번이라.

TextView TV = (TextView)findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

여기 약간의 도움말 기능이 있습니다.여러 언어를 사용하는 경우에 적합합니다!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

나는 항상 새로운 개념을 이해하려고 할 때 시각적인 예를 도움이 된다고 생각합니다.

배경색

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

전경색

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

조합

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

추가 연구

를 해 보는 것이 .TextPaint과 같습니다스. 사용 방법은 다음과 같습니다.

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

설정합니다.TextView는 확장 a를 합니다.ForegroundColorSpan당신의 문자를 위해.

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

일부 상황에서 사용할 수 있는 또 다른 방법은 Spannable(스패너블)을 사용하는 뷰의 속성에서 링크 색상을 설정하는 것입니다.

예를 들어 Spannable을 TextView에서 사용할 경우 XML에서 다음과 같이 링크 색상을 설정할 수 있습니다.

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

다음을 사용하여 코드에 설정할 수도 있습니다.

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);

코틀린 확장 기능이 있습니다.

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

텍스트 보기로 텍스트를 설정한 후 사용합니다.

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));

private SpannableString spannableString(String text, int start, int end) {
    SpannableString spannableString = new SpannableString(text);
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

출력:

enter image description here

문자열색상전달하여 텍스트색상을 설정합니다.

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

아래 코드를 호출하여 텍스트 보기 / 버튼 / 텍스트 편집 등에서 텍스트를 설정합니다.

텍스트 보기:

TextView txtView = (TextView)findViewById(R.id.txtView);

색이 있는 문자열 가져오기:

String name = getColoredSpanned("Hiren", "#800000");

텍스트 보기에서 텍스트 설정:

txtView.setText(Html.fromHtml(name));

다 했어요.

스패너블을 만드는 공장이 있는데, 출연진은 피하세요.

Spannable span = Spannable.Factory.getInstance().newSpannable("text");

수용된 답변에 덧붙이자면, 모든 답변들이 단지 다음과 같은 것만을 이야기하는 것처럼 보입니다: 만약 내가 원하는 색상이 정의되어 있다면 어떨까요?res/values/colors.xml?

예를 들어, 다음에 정의된 재료 설계 색상을 고려합니다.colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_blue_500">#2196F3</color>
</resources>

(android_material_design_colours.xml당신의 가장 친한 친구입니다)

으로.ContextCompat.getColor(getContext(), R.color.md_blue_500).Color.BLUE, 다음을 위해:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

다음이 됩니다.

wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

어디서 찾았습니까?

Textview Span

kotlin-ktx를 사용하면 쉽게 달성할 수 있습니다.

        bindView?.oneTimePasswordTitle?.text = buildSpannedString {
        append("One Time Password ")
        inSpans(
            ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
        ){
            append(" (As Registered Email)")
        }

    }

여기에 있는 몇몇 답변들은 최신이 아닙니다.대부분의 경우 링크에 사용자 지정 클릭 작업을 추가하기 때문입니다.

또한 설명서 도움말에서 제공하는 대로 스팬된 문자열 링크 색상은 기본값을 가집니다."이 속성이 테마에 정의되어 있는 경우 기본 링크 색상은 테마의 액센트 색상 또는 안드로이드:textColorLink입니다."

여기 안전하게 하는 방법이 있습니다.

 private class CustomClickableSpan extends ClickableSpan {

    private int color = -1;

    public CustomClickableSpan(){
        super();
        if(getContext() != null) {
            color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
        }
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        ds.setColor(color != -1 ? color : ds.linkColor);
        ds.setUnderlineText(true);
    }

    @Override
    public void onClick(@NonNull View widget) {
    }
}

그럼 쓰라고요.

   String text = "my text with action";
    hideText= new SpannableString(text);
    hideText.setSpan(new CustomClickableSpan(){

        @Override
        public void onClick(@NonNull View widget) {
            // your action here !
        }

    }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    yourtextview.setText(hideText);
    // don't forget this ! or this will not work !
    yourtextview.setMovementMethod(LinkMovementMethod.getInstance());

이것이 큰 도움이 되기를 바랍니다!

  1. 레이아웃에서 텍스트 뷰 작성
  2. 이 코드를 기본 활동에 붙여넣기

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

아래는 저에게 완벽하게 적합합니다.

    tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
    String originalText = (String)tvPrivacyPolicy.getText();
    int startPosition = 15;
    int endPosition = 31;

    SpannableString spannableStr = new SpannableString(originalText);
    UnderlineSpan underlineSpan = new UnderlineSpan();
    spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
    spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);

    spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    tvPrivacyPolicy.setText(spannableStr);

위 코드에 대한 출력

enter image description here

  • 저도 똑같은 문제가 생겼어요.
  • @Dano의 대답은 정말 정확합니다.하지만 저에겐 통하지 않는군요.
  • 그 후 ClickableSpan을 추가한 문제를 발견했습니다.그래서 다른 색(액센트색)으로 제 색이 바뀝니다.

쟁점.


SpanableStringBuilder는 ForegroundColorSpan 또는 UnderlineSpan 뒤에 클릭 가능한 Span을 추가해도 색상 및 선 긋기가 변경되지 않습니다.

해결책


1. 클릭 가능한 범위 포함

  • ClickableSpan 내에서 updateDrawState 메서드를 재정의할 수 있습니다.
  • updateDrawState 메서드에서는 슈퍼 콜백을 제거해야 합니다.
  • 그런 다음 필요에 따라 텍스트 페인트를 수정해야 합니다.

2. 클릭 가능한 범위 없음

  • ForegroundColorSpan 추가 텍스트 색상을 변경합니다.
  • 밑줄 간격을 추가하여 텍스트에 밑줄을 추가합니다.

개발자 문서에서 스패너블의 색상 및 크기를 변경하려면:

1- 클래스를 만듭니다.

    class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {

    override fun updateDrawState(textPaint: TextPaint?) {
        super.updateDrawState(textPaint)
        textPaint?.color = color
    } 
}

2 해당 클래스를 사용하여 스패너블을 만듭니다.

    val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
    RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
    titleNames.length - microbe.name.length, // start
    titleNames.length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)

코틀린에서 확장 기능을 사용할 수 있습니다.

fun CharSequence.colorizeText(
    textPartToColorize: CharSequence,
    @ColorInt color: Int
): CharSequence = SpannableString(this).apply {
    val startIndexOfText = this.indexOf(textPartToColorize.toString())
    setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}

용도:

val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))
viewBinding.myTextView.text = myTextToColorize

이제 CodeView 라이브러리를 사용하여 다양한 색상의 패턴을 쉽게 강조 표시할 수 있습니다. 예를 들어 텍스트 내부의 모든 URL을 쓰기만 하면 되는 파란색으로 강조 표시할 수 있습니다.

CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);

CodeView Repository URL: https://github.com/amrdeveloper/codeview

First Part **Second Part should be Bold** last Part

이 텍스트는 SpannableString을 사용하여 변경해야 합니다.

import android.graphics.Typeface.BOLD
import android.text.Spannable
import android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan

val firstPart = "First Part  "
val secondPart = "Second Part should be Bold"
val thirdPart = "  last Part"
val finalString = firstPart + secondPart + thirdPart

val sb: Spannable = SpannableString(finalString).also {
                // ... Change text Colour
                it.setSpan(
                    ForegroundColorSpan(getColor(requireContext(), R.color.pink)),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Make the text Bold
                it.setSpan(
                    StyleSpan(BOLD),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Change Background Colour
                it.setSpan(
                    BackgroundColorSpan(getColor(requireContext(), R.color.lightPink)),
                    finalString.indexOf(secondPart) - 1,
                    finalString.indexOf(secondPart) + secondPart.length + 1,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
}

yourTextView.text = sb

언급URL : https://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android

반응형