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 Making a Button Do Something

Arthur Podkowiak
Arthur Podkowiak
3,633 Points

Why cast showFactButton to a Button?

Why do we have to cast the showFactButton to be a button? For the factLabel we cast the method to find the id for the View to TextView because that's how we created our object, factLabel. But for the button, showFactButton, we initialized it as an object in the Button class already, so why do we need to typecast the findViewById method back to a Button when it is initialized as one?

1 Answer

Mainly, it's because findViewById has a declared return type of android.view.View. The Java type system isn't smart enough to read through your code and figure out that it's certainly a Button. The type system necessarily forgets a lot of type information so that it can generate generic code to handle anything that's a View, not just Buttons.

Arthur Podkowiak
Arthur Podkowiak
3,633 Points

Aha, I see! That makes sense, I guess I should have connected that the find"View"ById is used to searching for views meaning it is normal to the View class rather than the Button class, so we'd have to typecast it since there is no method for finding Button Ids anyways. Thanks a bunch!