Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to reference a button in Java created in XML?

 
Ryan Lemon
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm creating my first Android app and I'm simply wondering how I can reference a button I create in my activity_mail.xml in my MainActivity.java class so that I can change it's image.

I was thinking it'd look something like this after searching the net but I can't seem to figure it out: JavaButtonName = R.id.XMLButtonName
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I refer to this site: http://developer.android.com/guide/topics/ui/declaring-layout.html first because that site has a lot of great information so it should be your number one resource, but also because that page has an example of how to do what you want (about half way down the page in the Attributes section)

Basically, the R.id. value is just a unique number used to locate the View. You use the findViewById() method (found in a Context object, and an Activity is a Context, so you can call it directly on your Activity) to locate the View you need. It is returned as a generic View type, so if you need to use Button methods you will need to cast it.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic