Android view without xml

I need to create a view without XML. I am getting the view id using a method getID

for the view, but I am getting ResourceNotFoundException

. I tried using this ID for the method setID

, but it doesn't work anymore.

+2


source to share


4 answers


If you haven't already declared your view and put it in the layout XML file, you won't be able to get it with

findViewById(int)

If you are creating your view without XML, you must manage it without a resource ID. You just create a view and name it and then use the name to work with it.



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

However, would you like NOT to declare it in XML? Usually when you start a project, you cannot see how you can do anything with the XML layout, and select the programmatic representation of most views. After you move forward with a project or gather more experience, in almost all cases you see that you could do it with XML.

+1


source


I think the problem is as follows. When you call findViewById()

it looks for that view in the display tree. Thus, to get a view from the tree, you had to add your view to the tree using the addView () function. If you haven't, it may not be able to find the tree view.



+1


source


If you try to print getId(int)

in the view, do you get a valid ID?

Try to use findViewById(int)

in the correct context, eg.yourContext.findViewById(int);

0


source


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);

0


source







All Articles