Spannable WordtoSpan;
TextView tvView;
public void btnStart(View v)
{
tvView = (TextView)findViewById(R.id.tvTest);
changeColorOfText("I know just how to whisper, And I know just how to cry,I know just where to find the answers.");
}
int sIndexOfWord;
int fIndexOfWord;
private void changeColorOfText(String sentences)
{
String[] arrWords = sentences.split(" ");
WordtoSpan = new SpannableString(sentences);
int k = 1;
for(String word : arrWords) {
sIndexOfWord = sentences.indexOf(word);
fIndexOfWord = sIndexOfWord + word.length();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW), sIndexOfWord, fIndexOfWord, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvView.setText(WordtoSpan);
}
}, 2000*k++);
}
}
This code not work, just color the last text of sentence. How can i color word one by one with handler.postDelayed method.
Thanks.
may be you can try this: call setTextColor() method recursively at interval of 2 seconds
int k = 0;
private void setTxtColor(){
if(k < arrWords.length){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
sIndexOfWord = sentences.indexOf(arrWords[k]);
fIndexOfWord = sIndexOfWord + word.length();
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW), sIndexOfWord, fIndexOfWord, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvView.setText(WordtoSpan);
k++;
setTxtColor();
}
}, 2000);
}
}
The below displays words with green color as the foregr0und for words every 1 second.
Textview will have hello! displayed first with green color and after a delay for 1 second next word will be appended to the textview with green color. This repeats till it reaches the length of string s. If you don't want to append you just set text of the new word
_tv.setText(text); and remove the append part.
Also i have used a timer and set the text on the ui thread. You can also use a handler.
String s;
int _count=0;//counter
Timer _t;
TextView _tv;
String[] each;//holds each word in an array
Button b;
b= (Button) findViewById(R.id.button1);
_tv = (TextView) findViewById( R.id.tv );
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//s=et.getText().toString();
s="hello!. how are you";
_tv.setText("");
for(int i=0;i<s.length();i++)
{
each = s.split("\\s+");
}
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
if(_count<=each.length-1)
{
SpannableString text = new SpannableString(each[_count]);
text.setSpan(new ForegroundColorSpan(Color.GREEN), 0,text.length(), 0);
_tv.append(text);
_tv.append(" ");
System.out.println("................"+each[_count]);
_count=_count+1;
}
else
{
_t.cancel();
}
}
});
}
}, 1000, 1000 ); //change to 2000 for 2 second delay.
}
});