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 trialnemmes
749 PointsWhy must variables be declared for the TextView and Button?
To my untrained eye, it seems like declaring variables for the TextView and Button is redundant.
To my understanding, we are creating a variable, placing the view in it, then accessing the view via the variable.
Is there a reason why we don't just access the view directly?
Hope this question makes sense...
2 Answers
Harry James
14,780 PointsHey nemmes!
When we access a view directly, we call findViewById()
. Behind the scenes, this is quite costy in Android in terms of resources so we don't want to call the method that much.
Therefore, by storing the view in a variable once, we only call the method to find that view once, and we save on resources!
It's important to think in terms of resources when doing Mobile Development as we need to take into account battery life, slow devices and a range of other factors. We're all about making the best user experience so, we don't want a slow app!
Hopefully this will explain to you why we use a variable but if there's still something you don't quite understand, feel free to give me a shout and I'll be sure to help out :)
nemmes
749 PointsAh, I see! It's a matter of efficiency, then. Got it. Thanks!