contrapsych
contrapsych

Reputation: 1949

Finding child views from parent view created programmatically in Android

For an Android App, I'm using a GridView and extending BaseAdapter to organize its contents. For the function getView that I override in my extended BaseAdapter class, I create a LinearLayout, which I attach an ImageView and 3 TextViews to. Now, I need to implement convertView, but because I created my views programmatically, I didn't think I can use findViewById to find these child views to change their properties (like text and bitmaps).

I had the idea of assigning a unique ID pertaining to different types of views for each one when I create them (example: give my name textview the id of 1, description textview the id of 2, etc), but I was not sure if the ids have to be unique among every view, whether they're the same kind of view or not.

Ultimately, how do I find a child view that's part of a linearlayout view which were all created programmatically?

Upvotes: 4

Views: 7467

Answers (1)

Sergey Glotov
Sergey Glotov

Reputation: 20336

You can get children of LinearLayout via getChildAt() but it's hard to distinguish what child exactly you get.

I think assigning IDs is better way. You can assign IDs to your views and later get views via findViewById(). IDs doesn't need to be unique for each LinearLayout.

Something like this:

// Give more sensible names to ID's
int IMAGEVIEW_ID = 0;
int TEXTVIEW1_ID = 1;
int TEXTVIEW2_ID = 2;
int TEXTVIEW3_ID = 3;

imageView.setId(IMAGEVIEW_ID);
textView1.setId(TEXTVIEW1_ID);
textView2.setId(TEXTVIEW2_ID);
textView3.setId(TEXTVIEW3_ID);

...
// somewhere later
ImageView imageView = (ImageView) convertView.findViewById(IMAGEVIEW_ID);

Upvotes: 5

Related Questions