Android TextView partly gradient,
such as: "hello android hello kotlin", I want "kotlin" gradient, how can I do?
you can try like this programmatically using spannbleSting
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
String fullText = "hello android hello kotlin";
String gradientText = "kotlin";
// Find the starting index of the gradient text
int startIndex = fullText.indexOf(gradientText);
if (startIndex != -1) {
SpannableString spannableString = new SpannableString(fullText);
// Define the gradient color and other options
int[] gradientColors = {0xFF0000FF, 0xFF00FF00}; // Example: Blue to Green
Shader shader = new LinearGradient(0, 0, 0, textView.getTextSize(), gradientColors, null, Shader.TileMode.CLAMP);
// Apply the gradient color span to the desired part of the text
spannableString.setSpan(new ForegroundColorSpan(shader), startIndex, startIndex + gradientText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
}
}
private static class ForegroundColorSpanWithShader extends CharacterStyle implements UpdateAppearance {
private Shader shader;
ForegroundColorSpanWithShader(Shader shader) {
this.shader = shader;
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setShader(shader);
}
}
}