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 (2014) Improving Our Code Adding More Colors

Nhat Nguyen
Nhat Nguyen
4,669 Points

Why isn't the layout "final" when we change its background in the code challenge?

Hi, So in the videos, if we plan to change any properties of an element, we need to make it final. However, in the coding challenge, I see no "final" keyword there. Is it because in the videos, we change the properties in the onClick method and now we just change it in the onCreate? Hope you can explain it for me! Thank you

MealActivity.java
public class MealActivity extends Activity {

    public TextView foodLabel;
    public TextView drinkLabel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meal);

        foodLabel = (TextView) findViewById(R.id.foodTextView);
        drinkLabel = (TextView) findViewById(R.id.drinkTextView);
        RelativeLayout mealLayout = (RelativeLayout) findViewById(R.id.mealLayout);
        mealLayout.setBackgroundColor(Color.GREEN);
    }
}

1 Answer

Dan Johnson
Dan Johnson
40,533 Points

The final keyword, when used with a variable, prevents it from being assigned a new reference (or value in the case of primitive types). So in the case of dealing with properties of an object that was declared final, it doesn't really matter:

public class Application {
    public static void main(String[] args) {
        final StringBuilder builder = new StringBuilder("Hello");
        // Not allowed:
        // builder = new StringBuilder("Hello World");
        // Allowed:
        builder.append(" World");
    }
}

Variables are required to be final if they are to be used in an anonymous inner class (like what was used for the OnClickListener). Here's a post on stackoverflow detailing why