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) Basic Android Programming Accessing Views in Code

Herschel Greenspan
Herschel Greenspan
890 Points

How do i fix this line of code? I am completely lost.

Here is the code:

// declare our view variables and assign them the views form the layout file TextView factLabel= (TextView)findViewById(R.id.factTextView); Button showFactButton;

1 Answer

Iain Diamond
Iain Diamond
29,379 Points
TextView factLabel = (TextView) findViewById(R.id.factTextView);

Let's start by explaining the factLabel.

Somewhere in the activity is a text view with an id of factTextView. If you want to change label text we need to refer to it in code somehow. All the activity items are stored in a computer generated file known as 'R'. So, this means the fact text can be reached using R.id.factTextView. The method that does this is the findViewById. The value this method returns is stored in the factLabel variable which is of type TextView, which unfortunately doesn't match the output from findViewById so we need to change the output type by using type conversion. This is what the '(TextView)' before the function call is doing.

So to do the same for the Button showFactButton, well, the question says it has the id of showFactButton. This means its id will be R.id.showFactButton. We plug this into the method, remembering that we want something of type Button, which gives the final result of:

Button showFactButton = (Button) findViewById(R.id.showFactButton)

Hope this makes sense. iain