Android에서 TextView 범위의 색상 설정


206

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

텍스트의 일부가 파란색 인 Twitter 앱과 비슷한 작업을하고 싶습니다. 아래 이미지를보십시오 :

대체 텍스트
(출처 : twimg.com )

답변:


429

또 다른 대답은 매우 비슷하지만 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);

그러나 여러 단어의 색상을 어떻게 바꿀 수 있습니까?
— mostafa hashim

1
@mostafahashim은 3 행을 반복하여 여러 범위를 만듭니다. wordtoSpan.setSpan (new ForegroundColorSpan (Color.RED), 50, 80, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
— Ashraf Alshahawy

Kotlin + Spannable String 솔루션은 다음과 같습니다. stackoverflow.com/questions/4032676/…
— Dmitrii Leonov

81

다음은 약간의 도움말 기능입니다. 여러 언어가있을 때 유용합니다!

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);
}

37

새로운 개념을 이해하려고 할 때 항상 시각적 인 예가 도움이됩니다.

배경색

여기에 이미지 설명을 입력하십시오

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);

전경색

여기에 이미지 설명을 입력하십시오

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);

콤비네이션

여기에 이미지 설명을 입력하십시오

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);

추가 연구


29

더 많은 통제력을 원한다면 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);
    }
};

getColor (int id)는 Android 6.0 Marshmallow (API 23)에서 사용되지 않습니다. stackoverflow.com/questions/31590714/…
— Eka putra

클릭 리스너와 함께 좋은 답변.
— Muhaiminur Rahman 2016 년

20

확장 가능한 TextView텍스트를 설정 하고 텍스트를 정의 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);

감사! 먼저 텍스트를 TextView에 할당하지 않고도이 작업을 수행 할 수 있습니까?
— hpique

나는 나 자신을 잘 설명하지 않았다. 다시 말하겠습니다. 처음 3 줄이 필요합니까? 문자열에서 Spannable 객체를 직접 만들 수 없습니까?
— hpique

아니요, 전경색을 변경하려면 TextView의 텍스트를 버퍼 스패너 블에 저장해야합니다.
— Jorgesys

나는 색상과 같은 것을하고 싶습니다. 색깔 부분을 제외하고 모든 것을 굵게 표시하고 싶습니다. 그 부분은 기울임 꼴이되고 싶습니다. 어떻게 할 수 있습니까?
— Lukap

1
범위에서 클릭을 설정하는 방법은 무엇입니까?
— Rishabh Srivastava

13

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

예를 들어 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);

5

Spannable을 생성하는 팩토리가 있으며 다음과 같이 캐스트를 피하십시오.

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

1
SpannableFactory를 사용하는 방법을 설명해 주시겠습니까? "텍스트"는 어떻게 생겼습니까?
— Piotr

SpannableFactory로 Spannable을 만든 후 어떻게 사용합니까?
— MBH

5

문자열 과 색상 을 전달 하여 텍스트 색상 을 설정하십시오 .

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

아래 코드를 호출 하여 TextView / Button / EditText 등에 텍스트 를 설정하십시오 .

TextView :

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

컬러 문자열 가져 오기 :

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

TextView에서 텍스트 설정 :

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

끝난


4
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;
}

산출:

여기에 이미지 설명을 입력하십시오


Hasina 🤣
— Abu Nayem

3

모든 답변에 android.graphics.Color대해서만 이야기하는 것처럼 허용되는 답변에 추가하기 만하면 됩니다. 원하는 색상이에 정의되어 있으면 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);

내가 찾은 곳 :


2

여기에 Kotlin 확장 기능이 있습니다.

    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")
    }
}

텍스트를 TextView로 설정 한 후에 사용하십시오.

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

textViewTip.setColouredSpan("Warning", blueberry)

0
  1. ur 레이아웃으로 textview 만들기
  2. 이 코드를 ur MainActivity에 붙여 넣기

    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

0

아래는 나를 위해 완벽하게 작동합니다.

    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);

위 코드에 대한 출력

여기에 이미지 설명을 입력하십시오


0

여기에 일부 답변이 최신 상태가 아닙니다. 대부분의 경우 링크에 사용자 지정 클릭 동작을 추가 하기 때문에 .

또한 설명서 도움말에서 제공하는 스팬 문자열 링크 색상은 기본 색상입니다. "이 속성이 테마에 정의 된 경우 기본 링크 색상은 테마의 강조 색상 또는 android : 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());

이것이 강력히 도움이되기를 바랍니다!


0

개발자 문서에서 스패너 블의 색상과 크기를 변경하려면 다음을 수행하십시오.

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
)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.