2011-03-26 29 views
0
Hello All 

在我的android項目中,我想顯示一個特定的單詞說TRIAL在字符串中這是爲我的Trial.This試驗只是爲了好玩。 在android中如何實現這一點。跨度android中的某個單詞

我嘗試使用下面的代碼將只從15字符串格式爲30

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

請讓我知道如果我能做到這一點的機器人。

請轉發您的寶貴建議。

感謝提前:)

+0

我不得到什麼you're試圖做 – 2011-03-26 10:35:54

+0

我想給用戶一個設施一樣,如果有一個冗長的文字,他需要找到一些文字,特定搜索文本應是紅色的而在黑色休息:) – Remmyabhavan 2011-03-26 10:54:28

回答

0

嘗試使用的indexOf(字符串str)方法在String類。這會給你,你在你的Spannable搜索(這是一個擴展字符串)這個詞第一次出現。然後你就可以相應地適用您的色彩跨度。

public class Junk extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     TextView tv = (TextView) findViewById(R.id.textView1); 
     String tvText = "This is for my Trial.This Trial is just for fun. Just a Trial"; 
     tvText+="A Trial. Only a Trial. It's a Trial"; 
     String lookFor = "Trial"; 
     tv.setText(formatString(tvText, lookFor)); 
    } 

    private Spannable formatString(String targetStr, String lookFor) { 

     Spannable spanString = null; 
     spanString = new SpannableString(targetStr); 
     int fromIndex, startSpan, endSpan; 

     fromIndex = 0; 
     while (fromIndex < (targetStr.length() - 1)) { 
      startSpan = targetStr.indexOf(lookFor, fromIndex); 
      if (startSpan == -1) 
       break; 
      endSpan = startSpan + lookFor.length(); 
      spanString.setSpan(new ForegroundColorSpan(Color.BLUE), startSpan, 
        endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
      fromIndex = endSpan; 
     } 
     return spanString; 
    } 
} 

0

擴展在大鐮刀的回答了一下,用全部更換。

相關問題