To give text a color and font size in an Android app, you can use the SpannableStringBuilder
class to create a SpannableString
with the desired formatting, and then set the SpannableString
as the text of a TextView
.
Here's an example of how you could use the SpannableStringBuilder
class to set the text color and font size of a TextView
in an Android layout:
import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; import android.widget.TextView; TextView textView = findViewById(R.id.text_view); SpannableStringBuilder builder = new SpannableStringBuilder(); String text = "Hello, world!"; builder.append(text); int start = 0; int end = text.length(); builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, 0); builder.setSpan(new AbsoluteSizeSpan(20), start, end, 0); textView.setText(builder);
In this example, the ForegroundColorSpan
and AbsoluteSizeSpan
classes are used to set the text color and font size, respectively. The setSpan()
method is used to apply the spans to the SpannableStringBuilder
, and the setText()
method is used to set the SpannableStringBuilder
as the text of the TextView
.
Note that you can use different span classes to apply different types of formatting to text, such as background color, font style, or underline.