How to give multiple text colors Android TextView
How to Create multicolor Textview on Android:
We can change the color of Textview content using SpanbleString.
We can change the color of Textview content using SpanbleString.
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SpannableString ss = new SpannableString(getResources().getString(R.string.terms_and_conditions));
ClickableSpan clickableSpan1 = new ClickableSpan() {
@Override public void onClick(View textView) {
// startActivity(new Intent(MyActivity.this, NextActivity.class)); Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
@Override public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ClickableSpan clickableSpan2 = new ClickableSpan() {
@Override public void onClick(View textView) {
// startActivity(new Intent(MyActivity.this, NextActivity.class)); Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
@Override public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ss.setSpan(clickableSpan1, 27, 48, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(clickableSpan2, 51, 66, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.txt_terms);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
}
}
And Xml is following
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.mallem.androidapps.MainActivity">
<TextView android:id="@+id/txt_terms" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
No comments