Ogen
Ogen

Reputation: 6709

Android: Finding a view's id by supplying its own id

If I have ImageButton myPicture. Can I say myPicture = (ImageButton) findViewById(myPicture.getId());?

Is there anyway I can implement this?

Upvotes: 1

Views: 44

Answers (2)

Youans
Youans

Reputation: 5081

ofcourse you can't since myPicture in the right operand is still null this can cause NullPointerException and yet you didn't catch any ImageButton view you either create one programmatically

ImageButton imageButton=new ImageButton(this);

or you draw it on layout XML file and this find it by using findViewById(R.id.imageButtonId)

this will actually create a view of ImageButton then you can select it but by your way there isn't view to select yet

Upvotes: 0

Matt Clark
Matt Clark

Reputation: 28639

If the myPicture object already exists, why would you be recreating it?

Yes, this will work, if the myPicture objects has already been created in the app context, or been previously reference to an Id in your layout.

You can not use this as a first time initialization, because the object is null, you have to first get it from the layout.

Edit

In response to your comment above, instead of doing this 64 times, you could use an XML file to create a template layout, and then in your Java code, inflate the template layout inside of a loop, adding in the required information.

Upvotes: 3

Related Questions