Максим Зубков Максим Зубков - 5 months ago 16
Android Question

Add TextView at runtime in Adapter

append every message in array


m.getGenre()


as new message with TextView for every message in array i want to make TextView for it and append

this is CustomListAdapter inside it i want loop in array and append every item in array as new TextView

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<notofication> movieItems;
private final Context context;


public CustomListAdapter(Activity activity, List<notofication> movieItems,Context c) {
this.activity = activity;
this.movieItems = movieItems;
this.context = c;
}

@Override
public int getCount() {
return movieItems.size();
}

@Override
public Object getItem(int location) {
return movieItems.get(location);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);


TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

// getting movie data for the row
final notofication m = movieItems.get(position);







// title
title.setText(m.getTitle());



// rating
rating.setText(String.valueOf(m.getRating()));


String genreStr = "";
for (String str : m.getGenre()) {
//append every str as new textView
}


// release year
year.setText(m.getYear());

return convertView;
}

}


now the result will be something like this (its just example)

enter image description here

how can i make new textView for every message like this image

enter image description here

this is my code

String genreStr = "";
for (String str : m.getGenre()) {
//append every str as new textView
}


but i dont know how to make new TextView adn append it inside CustomAdapter

Answer

use this example

instead of this........

TextView genre = (TextView) convertView.findViewById(R.id.genre);

use this

LinearLayout mgenre = (LinearLayout) convertView.findViewById(R.id.genre);

Note:-in xml change TextView of id genre into Linear Layout with orientation vertical.

for(String genre:m.getGenre()){
    TextView text = new TextView(context);
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    text.setLayoutParams(p);
    text.setText(genre);
    text.setTextAppearance(R.style.boldText);

    mgenre.addView(text);
}

enjoy coding...........

Comments