Reputation: 10102
I have a poll of ID's (ids.xml
), and I assign id's for views I create dynamically. Now my question is pretty simple - assume I create a new view and assign it an id with setId()
in conjuction with R.id.uniqueId
. Later on, can I access the view with findViewById(R.id.uniqueId)
?
If so, what could be the reason it returns null?
Here is a toy example: UPDATED
LinearLayout l = new LinearLayout(this);
l.setId(R.id.mId);
setContentView(l); //i see on screen the views added to 'l'
l = (LinearLayout) findViewById(R.id.mId); //it returns null :(
How come it does not register\map the assgined ID to the view it was assigned?
Upvotes: 0
Views: 2350
Reputation: 163
encountered this many times, try cleaning your project by making a clean, Also check findViewById() returns null for custom component in layout XML, not for other components
Upvotes: 1
Reputation: 413
From what you have given us it appears that the view is never added to the Activity's view. This is necessary as findViewById uses the activity's view as a parent to find a child view with that Id.
If you are creating the view you can always create it as a member variable and refer to it that way if you are going to be adding it to a view at a later time. Please note that the view must be added after the id has been set.
Upvotes: 0
Reputation: 6591
Does your desired view have a parent view that you could use to call parent.findViewById on? That may help narrow your problem down.
One thing I noticed that's missing from your brief example: you need to make sure you're adding the new LinearLayout to the view hierarchy before you will be able to find it with findViewById:
findViewById(R.id.parent).addView(l)
You can also use the hierarchy viewer to take a look and see if everything's being set up properly.
Upvotes: 2