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!

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 Dynamically Changing the Background Color

George Thomas
George Thomas
768 Points

I am trying to change the background color of theRelativeLayout variable named mealLayout

I keep getting an error. mealLayout = findViewById(R.id.mealLayout) as RelativeLayout mealLayout!!.setBackgroundColor(Color.GREEN)

This returns an error; why?

I cannot change the background of the RelativeLayout variable named mealLayout.

import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import android.widget.RelativeLayout
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import java.util.*

class MealActivity : Activity() {
  var mealLayout: RelativeLayout? = null

  override fun onCreate(savedInstanceState: Bundle) {

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

1 Answer

Boban Talevski
Boban Talevski
24,793 Points

The answer is in the following challenge, some Kotlin challenges seem a bit buggy and/or weird :). I have posted it here as well.

The correct way to do what the challenge is asking here is

mealLayout.backgroundColor = Color.GREEN

And it didn't work for me in the app in Android Studio 2.3.