source

여러 색상의 텍스트가 있는 단일 텍스트 보기

ittop 2023. 9. 9. 10:16
반응형

여러 색상의 텍스트가 있는 단일 텍스트 보기

제목에서 알 수 있듯이, 하나의 텍스트 뷰 요소에서 두 가지 다른 색상의 캐릭터를 달성할 수 있는지 알고 싶습니다.

네, 포맷을 하시면String와 함께htmlfont-color속성을 메소드에 전달합니다.Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

HTML을 사용하지 않고 여러 색으로 선을 인쇄할 수 있습니다.

TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");        

word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");        

wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);

저는 이렇게 해왔습니다.

Check reference

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

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");
String surName = getColoredSpanned("Patel","#000080");

서로 다른 색을 가진 두 문자열의 텍스트 보기에 텍스트를 설정합니다)를 설정합니다.

txtView.setText(Html.fromHtml(name+" "+surName));

다 했어요.

사용가능Spannable효과를 당신의 것에 적용하다,TextView:

이것은 단지 a의 첫부분을 색칠하는 나의 예입니다.TextViewtext (HTML 예제와 같이 문자열로 하드 코딩하는 대신 동적으로 색상을 설정할 수 있습니다!)

    mTextView.setText("Red text is here", BufferType.SPANNABLE);
    Spannable span = (Spannable) mTextView.getText();
    span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
             Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

이 예에서는 0xFF를 대체할 수 있습니다.FF0000(a 포함)getResources().getColor(R.color.red)

스패너블 스트링빌더 사용

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

내가 해봤으니 해보세요.

TextView textView=(TextView)findViewById(R.id.yourTextView);//init

//here I am appending two string into my textView with two diff colors.
//I have done from fragment so I used here getActivity(), 
//If you are trying it from Activity then pass className.this or this; 

textView.append(TextViewUtils.getColoredString(getString(R.string.preString),ContextCompat.getColor(getActivity(),R.color.firstColor)));
textView.append(TextViewUtils.getColoredString(getString(R.string.postString),ContextCompat.getColor(getActivity(),R.color.secondColor)));

TextViewUtils 클래스 안에 다음 메서드를 추가합니다.

 /***
 *
 * @param mString this will setup to your textView
 * @param colorId  text will fill with this color.
 * @return string with color, it will append to textView.
 */
public static Spannable getColoredString(String mString, int colorId) {
    Spannable spannable = new SpannableString(mString);
    spannable.setSpan(new ForegroundColorSpan(colorId), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    Log.d(TAG,spannable.toString());
    return spannable;
}

문자열 파일에서 문자열을 사용하는 것이 좋습니다. 다음과 같습니다.

    <string name="some_text">
<![CDATA[
normal color <font color=\'#06a7eb\'>special color</font>]]>
    </string>

용도:

textView.text=HtmlCompat.fromHtml(getString(R.string.some_text), HtmlCompat.FROM_HTML_MODE_LEGACY)

@Swapnil Kotwal의 답변 Kotlin 버전.

안드로이드 스튜디오 4.0.1, 코틀린 1.3.72

val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText

val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)

val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

언제부터 가능한지는 모르겠지만, 당신은 간단히 추가할 수 있습니다.<font> </font>텍스트당 색상이 자동으로 변경되는 string.xml로 이동합니다.스패너블 텍스트 등의 코드를 추가할 필요가 없습니다.

<string name="my_formatted_text">
    <font color="#FF0707">THIS IS RED</font>
    <font color="#0B132B">AND NOW BLUE</font>
</string>

나는 이 질문과 비슷한 다른 질문에 대한 코드를 몇 개 적었지만, 그 질문이 중복되어 거기에 답할 수 없어서 같은 요구 사항을 찾는 사람이 있다면 여기에 내 코드를 넣는 것입니다.

코드가 완전히 작동하지 않아 약간의 변경을 해야 작동할 수 있습니다.

코드는 다음과 같습니다.

스패너블 텍스트를 사용하는 @Graeme 아이디어를 사용했습니다.

String colorfulText = "colorfulText";       
    Spannable span = new SpannableString(colorfulText);             

    for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
        span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                     
    }   

    ((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);

랜덤 색상 방법:

  private int getRandomColor(){
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

Kotlin과 Extensions를 사용하면 색 텍스트를 정말 쉽고 깨끗하게 추가할 수 있습니다.

파일 만들기 텍스트 보기 내용을 포함한 Extensions.kt

fun TextView.append(string: String?, @ColorRes color: Int) {
    if (string == null || string.isEmpty()) {
        return
    }

    val spannable: Spannable = SpannableString(string)
    spannable.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(context, color)),
        0,
        spannable.length,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    append(spannable)
}

이제는 색으로 텍스트를 붙이기가 정말 쉽습니다.

textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)

기본적으로 @Abdul Rizwan 답변과 동일하지만 Kotlin, extension, 일부 validation 및 내부 extension을 사용하여 색상을 획득합니다.

코틀린 앤서

fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
    val spannableStr = SpannableString(tv.text)

    val underlineSpan = UnderlineSpan()
    spannableStr.setSpan(
        underlineSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
    spannableStr.setSpan(
        backgroundColorSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val styleSpanItalic = StyleSpan(Typeface.BOLD)
    spannableStr.setSpan(
        styleSpanItalic,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    tv.text = spannableStr
}

그런 다음 위의 기능을 호출합니다.둘 이상의 전화를 걸 수 있습니다.

setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)

출력 : 밑줄과 다른 색상을 서로 볼 수 있습니다.

텍스트 색상 및 텍스트 크기를 지정하려면strings.xml그런 다음 아래 코드를 확인합니다.

<string name="txt_my_string">
    <font fgcolor='#CFD8DC' > Text with given color </font> // Custom text color
    <font size="14" > Text with given size </font> // Custom Text size
    <font fgcolor='#3A55EA' size="14" > Text with given color and size </font> // Custom text color and size
</string>

쉽게 이해하길 바라요 :)

시도해 보기:

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
      "<small>" + description + "</small>" + "<br />" + 
      "<small>" + DateAdded + "</small>"));

HTML 형식 구문 분석보다 빠르기 때문에 가능한 경우 HTML 형식 대신 SpannableBuilder 클래스를 사용합니다.Github에서 "SpanableBuilder vs HTML" 벤치마크를 확인해 보십시오. 감사합니다!

멋진 대답들!Spannable을 사용하여 무지개 색 텍스트를 만들 수 있었습니다(어떤 색 배열에서도 이 작업이 반복될 수 있음).내 방법은 이렇습니다. 만약 누군가에게 도움이 된다면요.

private Spannable buildRainbowText(String pack_name) {
        int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
        Spannable word = new SpannableString(pack_name);
        for(int i = 0; i < word.length(); i++) {
            word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return word;
    }

그리고 그냥 Text를 설정합니다(buildRainboxText(pack_name)).제가 입력하는 모든 단어는 15자 미만이며 5가지 색상만 3번 반복합니다. 사용자가 사용할 수 있도록 배열의 색상/길이를 조정해야 합니다!

if (Build.VERSION.SDK_INT >= 24) {
     Html.fromHtml(String, flag) // for 24 API  and more
 } else {
     Html.fromHtml(String) // or for older API 
 }

24 API 이상용(플래그)

public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;

추가 정보

로 FROM_HTML_OPTION_USE_CSS_COLORS가 24로 CSS에서 색상을 정의할 수 있습니다. FROM_HTML_OPTION_USE_CSS_COLORS로 색상을 정의할 수 있습니다.font color="더 합니다 - 이 있고 태그를 표시하고 때 - html의 위에 fragment를 됩니다. html의 를 추가하면 .

이렇게 문자열을 스패너블로 변환하기 위한 공통 기능을 만듭니다.

//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement

fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
    val wordtoSpan: Spannable =
        SpannableString(s)
    wordtoSpan.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
        start,
        end,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    view.text = wordtoSpan
    }

우리는 이와 같은 요구 사항으로 어디서나 사용할 수 있습니다.

 SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number :   " + "123456789")

 SpannableStringWithColor(tvEmail,0,5,"Email :   " + "abc@gmail.com" "))

 SpannableStringWithColor(tvAddress,0,8,"Address :   " + "Delhi India")

Kotlin의 Builder 함수:

  val text = buildSpannedString {
      append("My red text")
      setSpan(
          ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.red)),
          3,
          6,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
      )
  }
  textView?.setText(text)

코틀린의 경우:

@JvmStatic
    @BindingAdapter(
        "app:txt1",
        "app:txt2",
        "app:color1",
        "app:color2",
        requireAll = false
    )
    fun setColors(
        txtView: AppCompatTextView,
        txt1: String,
        txt2: String,
        color1: Int,
        color2: Int
    ) {
        txtView.setColors(txt1 = txt1, txt2 = txt2, color1 = color1, color2)
    }


fun AppCompatTextView.setColors(txt1: String, txt2: String, color1: Int, color2: Int) {


        val word: Spannable = SpannableString(txt1)

        word.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(this.context, color1)),
            0,
            word.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        this.text = word
        val wordTwo: Spannable = SpannableString(txt2)

        wordTwo.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(this.context, color2)),
            0,
            wordTwo.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        this.append(wordTwo)

    }


<androidx.appcompat.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:txt1="@{}"
            app:txt2="@{}"
            app:color1="@{}"
            app:color2="@{}" />

Spannable을 사용하여 색을 변경하고 Regex를 사용하여 변경할 텍스트를 찾는 것이 가장 좋습니다.HtmlCompat는 텍스트의 구조를 수정하기 때문에 사용하는 것을 추천하지 않습니다.

텍스트 추가를 수정할 때

textView.setText("textExample", BufferType.SPANNABLE)

정규 표현식과 색상을 준비합니다.

val regex = Regex("Example")
val color = ContextCompat.getColor(requireContext(), R.color.red)

또한 단순화하기 위해 함수를 만드는 것을 추천합니다.

private fun applyTint(textView:TextView, regex:Regex, intColor:Int) {

    val span : Spannable = textView.text.toSpannable()
    val values = regex.findAll(textView.text)

    for(value in values.iterator()){
        val range = value.range
        span.setSpan(
            ForegroundColorSpan(intColor),
            range.first,
            range.last+1,
            Spannable.SPAN_COMPOSING
        )
    }
}

그리고 마침내 당신을 function이라 부릅니다.

applyTint(textView, regex, color)

결과는 다음과 같습니다.

CodeResult

정규 표현식에 대한 자세한 정보가 필요한 경우 https://developer.android.com/reference/java/util/regex/Pattern#summary-of-regular-expression-constructs 설명서를 참조하십시오.

subscription = none이면 "Active(활성)", 그렇지 않으면 "Inactive(비활성)" 상태로 표시됩니다.

if (it.data?.memberInfo?.subscription == "none") {
        val text = "<font color=#4d4d4d>Status: </font> <font color=#EB5757>Inactive</font>"
        binding.status.text = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY)
    } else {
        val text = "<font color=#4d4d4d>Status: </font> <font color=#00AA0E>Active</font>"
        binding.status.text = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY)
    }

출력:enter image description here

언급URL : https://stackoverflow.com/questions/6094315/single-textview-with-multiple-colored-text

반응형