Arutha
Arutha

Reputation: 26488

Android view without xml

I need to create view without XML. I retrieve the view ID by the getID method of the View but I get a ResourceNotFoundException. I tried to use to fix this ID the setID method but it doesn't work anymore.

Upvotes: 2

Views: 5324

Answers (4)

srirama
srirama

Reputation: 11

I think the problem is following. When you call findViewById() it searches for that view in the display tree. So to get the view from the tree you should have already added your view to the tree by using function addView(). If you have not done this it may not be able to find the view in the tree.

Upvotes: 1

Thizzer
Thizzer

Reputation: 16663

If you try to print the getId(int) of the View are you getting a valid id?

Try to use the findViewById(int) in the correct context e.g. yourContext.findViewById(int);

Upvotes: 0

DigitalKrony
DigitalKrony

Reputation: 75

it's easy.

lv = new ListView(this); lv.setId(android.R.layout.simple_list_item_1);

SimpleCursorAdapter ca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, from, to);

Upvotes: 0

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 16357

If you haven't declared your view and put id on it in layout XML file, you can't retrieve it with

findViewById(int)

If you create your view without XML, you should manage it without resource id. You just create the view and name it, then use the name to operate with it.

You can always pass reference of it to other classes, or make it accessible through the class that created it.

Still, you would you want to NOT declare it in XML? Usually, when you start a project, you can't see how you can do something with XML layout, and choose to create most views programmatically. After you move forward with the project, or gather more experience, in pretty much all the cases, you see you could have done it with XML.

Upvotes: 1

Related Questions