Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App with Kotlin Improving Our Code Adding Colors

George Popovich
George Popovich
15,055 Points

Having troubles with 'Adding Colors' exercise...

So I have absolutely no clue what is wrong with my code, but it throws the Bummer! exception:

The error:

MealActivity.kt:17:17: error: unresolved reference: setTextColor foodLabel!!.setTextColor(Color.BLUE) ^ MealActivity.kt:18:18: error: unresolved reference: setTextColor drinkLabel!!.setTextColor(Color.GRAY)

My code:

MealActivity.kt
import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import android.widget.RelativeLayout
import android.graphics.Color

class MealActivity : Activity() {
  override fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_meal)

    val foodLabel = findViewById(R.id.foodTextView) as TextView
    val drinkLabel = findViewById(R.id.drinkTextView) as TextView
    val mealLayout = findViewById(R.id.mealLayout) as RelativeLayout

    mealLayout.backgroundColor = Color.RED
    foodLabel.setTextColor(Color.BLUE)
    drinkLabel.setTextColor(Color.GRAY)

  }
}
Scott Junner
Scott Junner
9,010 Points

Is it setTextColor() or textColor()? I have not done any android work using Kotlin but I remember something like that being the case in a demo I watched.

George Popovich
George Popovich
15,055 Points

Scott Junner thanks, at first I thought I was just stupid but actually in Android Studio you have to write:

foodLabel.setTextColor(BLUE)

However in the exercise you have to write:

foodLabel.textColor = Color.BLUE

Which leads me to believe that the exercise is either outdated or broken

2 Answers

Scott Junner
Scott Junner
9,010 Points

It is the difference between writing in Java and writing in Kotlin. In Java you set the text color by calling the setTextColor() method. As seen here.

But in Kotlin you access the attribute directly as you can see a few times in this tutorial.

The exercise is very new and not broken. You are facing the difficulty of having extensive Java documentation and limited Kotlin Documentation.

Agree with George that exercise is a bit confusing. In the tutorial to this video the code we used was:

showFactButton!!.setTextColor(color)

So it was logical to use setTextColor in the exercise as well.