Using Spannable String in Android
SpannableString can be used to style texts in textview. You can style individual words in textview.
TextView tv = (TextView) findViewById(R.id.textView);
String myString = "Hello World";
SpannableString ss= new SpannableString(myString);
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(), 0);
//make the spannable string bold.
//first parameter is to style the text
//second parameter is 0 indicating the index from which the text should be styled.
//third parameter is the legth of the spannable string.
ss.setSpan(new StyleSpan(Typeface.ITALIC), 0, ss.length(), 0);
//make the spannable string italic
ss.setSpan(new ForegroundColorSpan(Color.BLUE), 0, ss.length(), 0);
//change the color of the spannable string
tv.setText(ss);
Make Spannable String Clickable
ss.setSpan(MyClickableSpan(ss) , 0, ss.length(), 0);
class MyClickableSpan extends ClickableSpan
{
String clicked;
//Constructor to receive the clicked text
public MyClickableSpan(String string) {
super();
clicked =string;
}
// action to be performed on click
public void onClick(View tv) {
Toast.makeText(MainActivity.this,clicked ,Toast.LENGTH_SHORT).show();
}
//update the drawable state of the text
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.BLUE);
//set text color
ds.setStrokeWidth(15f);
//set stroke width
ds.setUnderlineText(true);
// set to false to remove underline
}
}
No comments:
Post a Comment