Saturday 21 July 2018

Spannable TextView

XML

<?xml version="1.0" encoding="utf-8"?><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=".MainActivity">

    <TextView        android:id="@+id/tvMessage"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        android:textSize="30sp"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


JAVA

import android.graphics.Color
import android.graphics.Typeface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvMessage.text = generateCenterSpannableText()


    }

    private fun generateCenterSpannableText(): SpannableString {

        val s = SpannableString("I just have one question about colors template. For the LineChart, it is possible to show different colors : one for each line, but is it possible to show different colors for the same line ? I would like to draw different colors for circles, lines and also for the background under the line when the 'filled' option is enabled. I see that I can redefine the Paint object for the circles and change their color, but I can't do the same for lines and filled background, am I wrong ?")
        s.setSpan(RelativeSizeSpan(1.7f), 0, 2, 0)
        s.setSpan(StyleSpan(Typeface.NORMAL), 2, s.length - 1, 0)
        s.setSpan(ForegroundColorSpan(Color.GRAY), 14, s.length - 15, 0)
        s.setSpan(RelativeSizeSpan(.8f), 14, s.length - 15, 0)
        s.setSpan(StyleSpan(Typeface.ITALIC), s.length - 14, s.length, 0)
        s.setSpan(ForegroundColorSpan(getHoloBlue()), s.length - 14, s.length, 0)
        return s
    }

    fun getHoloBlue(): Int {
        return Color.rgb(51, 181, 229)
    }
}

No comments:

Post a Comment