Custom Rows in ListView with Custom Adapter

I made the following adapter, which I used earlier, to create strings that are the same all the time. I removed the creation of text views and images.

What I want to achieve is to create different lines depending on the key. A line can contain text and an image, and in another line only text. How can I do this?

public class DetailsListAdapter extends ArrayAdapter<ArrayList<String>> { private Context context; private ArrayList<String> keys; public DetailsListAdapter(Context context, ArrayList<String> keys) { super(context,R.layout.details); this.context = context; this.keys = keys; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.details, null); return v; } @Override public int getCount(){ return keys.size(); } } 
0
source share
2 answers

To inflate different layouts for strings, you need to override getViewItemType and getViewTypeCount .

You should watch the video in the link.

http://www.youtube.com/watch?v=wDBM6wVEO70

 private static final int TYPE_ITEM1 = 0; private static final int TYPE_ITEM2 = 1; private static final int TYPE_ITEM3 = 2; 

Then

 int type; @Override public int getItemViewType(int position) { if (position== 0){ type = TYPE_ITEM1; } else if (position == 1){ type = TYPE_ITEM2; } else { type= TYPE_ITEM3 ; } return type; } @Override public int getViewTypeCount() { return 3; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; LayoutInflater inflater = null; int type = getItemViewType(position); // instead of if else you can use a case if (convertView == null) { if (type == TYPE_ITEM1 { //infalte layout of type1 convertView = mInflater.inflate(R.layout.layouttype1, parent, false); } if (type == TYPE_ITEM2) { //infalte layout of type2 convertView = mInflater.inflate(R.layout.layouttype2, parent, false); } else { //infalte layout of normaltype convertView = mInflater.inflate(R.layout.layouttype3, parent, false); } ...// rest of the code return convertView; } 
+1
source

override getViewTypeCount inside this function returns the number of views you want to use inside the listview.

Override getItemViewType(int position) inside this write your logic to get the view type.

 @Override public int getViewTypeCount() { return 2; //return 2, in case you have two types of view } @Override public int getItemViewType(int position) { return (contition) ? R.layout.layout1 : R.layout.layout2; //return 2, in case you have two types of view } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = (convertView == null) ?View.inflate(context, getItemViewType(position), null) : convertView; return convertView; } 
+1
source

Source: https://habr.com/ru/post/972550/


All Articles