how to dynamically create xml layout multiple times inside getview() method in android?

596 views Asked by At

I have already created xml-layout file which contain View like comment box. I want to create dynamically layout (comment box) multiple times inside getView() method. How can i create it dynamically inside getView() method?

Here inside getview() method i have used code for dynamically generate particular View multiple times but it doesn't work. Please give me suggestion.

My adapter code link is below:

http://pastebin.com/aAYdPbn9

1

There are 1 answers

3
André Diermann On BEST ANSWER

I see three approaches for you. As discussed in the comments the title of your question is misleading, so this is what I assume:

  • you have a list of cards you want to display
  • each card may have a list of comments

So the underlying problem is, that you have a two-dimensional data structure, which you want to display using a one-dimensional UI component, in your case a ListView.

You can solve your problem by:

  1. Using an ExpandableListView, where the cards are the parent and the comments are the child elements. See [1] for an example.

  2. Flatten your data hierarchy. So you only have a list of items, where the cards are somehow treated as "headers" or "separators" for your comments. You need to overwrite [2], in that case your Adapter is capable of returning two different views. In the getView() method you then need to do something like:

    if(list.get(position) instanceOf Card) return getCardView(...); else if(list.get(position) instanceOf Comment) return getCommentView(...);

  3. Render the comments dynamically into a container within the card view. So in your layout file for your card view use a ViewGroup, e.g. a LinearLayout and give it a unique id, like "llComments". Have a separated layout file for your comments. Then in your current code you can inflate this file and just add the returned view to the container (llComments). I think this is the solution you are looking for. So, in your code, do something like:

    View commentConvertView = inflater.inflate(R.layout.list_item_comment, ...); ViewGroup comments = (ViewGroup) convertView.findViewById(R.id.llComments); comments.removeAllView; for(list.get(position).getComments()){ //bind the data to commentConvertView comments.add(commentConvertView); }

[1] http://www.vogella.com/tutorials/AndroidListView/article.html#expandablelistview_concept [2] http://developer.android.com/reference/android/widget/BaseAdapter.html#getViewTypeCount()