Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!