What pattern do I have to use, if I have ListView in which ImageView and like 500 different icons that could be set on that ImageView. Should I just write If/Switch statement, or there is another way/pattern to do it?. Thanks in advance!
Let me assume that you know what icon(I mean the name of icon) to be loaded into the imageView and those icons are available in your drawable resource folder. In this case
#Override
public void onBindViewHolder(final RecyclerAdapter.ViewHolder holder, int position) {
DataItem dataItem = dataList.get(holder.getAdapterPosistion());
try {
int resID = activityContext.getResources().getIdentifier(dataItem.getIconName() , "drawable"/**resource folder name*/, activityContext.getPackageName());
holder.imageView.setBackgroundResource(resID);
} catch (Exception e) {
throw new RuntimeException("Error getting Resource ID.", e)
}
}
Where are these icons that you want to set? you are getting them from server or they are stored locally in your application file? or they are from user phone gallery?
Here is the code you want for your adapter:
public class MyAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<String> mIconNames;
public MyAdapter(Context context) {
mContext = context;
mIconNames = getIconNames();
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mIconNames.size();
}
#Override
public Object getItem(int position) {
return mIconNames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.your_layout, parent, false);
ImageView thumbnailImageView =
(ImageView) rowView.findViewById(R.id.your_image_view_id);
Picasso.with(mContext).load(mIconNames.get(position)).placeholder(R.mipmap.ic_launcher).into(thumbnailImageView);
return rowView;
}
//this method builds your icon names
private ArrayList<String> getIconNames() {
ArrayList<String> iconNames = new ArrayList<>();
int numberOfIcons = 99;
String iconBaseName = "icon";
for (int i = 1; i < numberOfIcons; i++) {
iconNames.add(iconBaseName + i);
}
return iconNames;
}
}
Related
I am trying to display a ListView of some docs and images with different layouts.
it worked for docs but images are still not showing.
I have used the .contains method to check if the item is doc or image. Help me with this.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
String fileName = uriList.get(position).getFileName();
return viewSetup(position, layoutInflater, fileName);
}
private View viewSetup(final int position, LayoutInflater layoutInflater, String fileName) {
if (fileName.contains(".png") || fileName.contains(".jpg") || fileName.contains(".jpeg")) {
View inflate = layoutInflater.inflate(R.layout.main_list_item_img, null, false);
ImageView imageView = inflate.findViewById(R.id.imgPrev);
Glide.with(activity).load(uriList.get(position).getDownloadLink()).into(imageView);
itemSetup(position, fileName, inflate);
return inflate;
} else {
View inflate = layoutInflater.inflate(R.layout.main_list_item_docs, null, false);
itemSetup(position, fileName, inflate);
return inflate;
}
}
private void itemSetup(final int position, String fileName, View inflate) {
TextView title = inflate.findViewById(R.id.uriTitle);
TextView desc = inflate.findViewById(R.id.uriDesc);
ImageView download = inflate.findViewById(R.id.download);
TextView createdOn = inflate.findViewById(R.id.createdOn);
title.setText(fileName + "");
desc.setText(uriList.get(position).getDescription());
createdOn.setText(uriList.get(position).getSendTime());
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savefile(uriList.get(position).getDownloadLink());
}
});
}
I think there is a problem in your image loading. You can use Picasso.
Picasso.with(activity).load(yourUrl).
placeholder(R.drawable.image_loader).into(myImage);
You need to use type variable you can check how I did in below example :-
public class JobsAdapter extends BaseAdapter {
private Activity context;
private LinkedList<KeyValuesPair> listItemArrayList;
private LinkedList<Integer> type;
private LayoutInflater inflater;
public JobsAdapter(Activity context, LinkedList<KeyValuesPair> objects, LinkedList<Integer> type) {
this.context = context;
this.listItemArrayList = objects;
this.type = type;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return type.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean isEnabled(int position) {
return type.get(position) != 0;
}
#TargetApi(Build.VERSION_CODES.O)
public View getView(int position, View convertView, ViewGroup parent) {
// used new view instead of convertView so the spinner could support multiple views
View view = null;
// if type is equals to 0 it will load jobs header else jobs child
if (type.get(position) == 0) {
view = inflater.inflate(R.layout.lv_header, null, false);
TextView header = view.findViewById(R.id.jobsHeading);
header.setText(listItemArrayList.get(position).getValue());
if (position == 0) {
header.setTextSize(16);
header.setTypeface(context.getResources().getFont(R.font.raleway_regular));
header.setTextColor(context.getResources().getColor(R.color.colorPrimaryDark));
} else {
header.setTextColor(context.getResources().getColor(R.color.colorBlack));
}
} else if (type.get(position) == 1) {
view = inflater.inflate(R.layout.lv_child, null, false);
TextView child = view.findViewById(R.id.jobsChild);
child.setText(listItemArrayList.get(position).getValue());
}
return view;
}
}
I'm doing an app that uses BaseAdapter to see installed app in an Android device.
In this Listview there are more items, but in the adapter there are only two, and from the second (the package name) I get the other ones
I'm searching a way to sort the items of this adapter for an item that is in the listview, but not in the adapter. Here there is my code:
class AppsAdapter extends BaseAdapter{
private Context mContext;
private List<Pair<String, List<String>>> mAppsWithPermission;
AppsAdapter(Context context, List<Pair<String, List<String>>> appsWithPermission) {
mContext = context;
mAppsWithPermission = appsWithPermission;
}
static class ViewHolder {
TextView appName;
TextView appPermissions;
ImageView appIcon;
TextView Lines;
}
#Override
public int getCount() {
return mAppsWithPermission.size();
}
#Override
public Object getItem(int position) {
return mAppsWithPermission.get(position);
}
#Override
public long getItemId(int position) {
return mAppsWithPermission.get(position).hashCode();
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.appName = convertView.findViewById(R.id.list_item_appname);
holder.appPermissions = convertView.findViewById(R.id.list_item_apppermissions);
holder.appIcon = convertView.findViewById(R.id.list_item_appicon);
holder.Lines = convertView.findViewById(R.id.list_item_lines);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Pair<String, List<String>> item = mAppsWithPermission.get(position);
final PackageManager packageManager = mContext.getPackageManager();
String mAppPer = item.second.toString();
int lineCount = holder.appPermissions.getLineCount();
Log.v("LINE_NUMBERS", lineCount+"");
String strI = Integer.toString(lineCount);
holder.Lines.setText(strI);
if (mAppPer.matches("")) {
holder.Lines.setText("0");
}
});
return convertView;
}
}
When you see "item.second" it's the package name.
As you can think, I'm trying to sort the entire adapter for the descendant value of holder.lines (so StrI).
This is a different question from the others that talks about sorting an adapter, because I want to sort the adapter for an external value.
If you need further informations, you've just to ask me.
I'm trying to show images that are read from a url, they are more than an image so I had to put all of them in an arraylist and then make the images display in a gridview, for some reason it's not showing anything, the gridview is completely blank, please advise what am I doing wrong.
BottomSheetDialog_Smiles.java
Communicator.getInstance().on("subscribe start", new Emitter.Listener() {
#Override
public void call(Object... args) {
try{
JSONDictionary response = (JSONDictionary) args[0];
String str = response.get("emojiPack").toString();
JSONArray emojies = new JSONArray(str);
for(int i=0;i<emojies.length();i++){
JSONObject response2 = (JSONObject)
emojies.getJSONObject(i);
emojiModel = new EmojiModel((String) response2.get("urlFile"));
emojiUrl = emojiModel.getEmojiFile();
Picasso.with(getApplicationContext()).load(emojiUrl);
JSONDictionary t = JSONDictionary.fromString(response2.toString());
emojiModel.init(t);
emojieModels.add(new EmojiModel(emojiUrl));
}
EmojiAdapter emojiAdapter = new EmojiAdapter(getApplicationContext(),
emojieModels);
gridView2.setAdapter(emojiAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
EmojiAdapter emojiAdapter = new EmojiAdapter(getApplicationContext(),
emojieModels);
gridView2.setAdapter(emojiAdapter);
EmojiAdapter.java
public class EmojiAdapter extends ArrayAdapter<EmojiModel> {
Context context;
ArrayList<EmojiModel> list = new ArrayList<>();
public EmojiAdapter(Context context,ArrayList<EmojiModel> list) {
super(context, R.layout.smiles_items_layout, list);
this.context = context;
this.list = list;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater o =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = o.inflate(R.layout.gifts_layout_2, parent , false);
ImageView imageView = (ImageView) v.findViewById(R.id.smile_image_view);
imageView.setImageResource(Integer.parseInt((list.get(position)).urlFile));
return v;
}
}
EmojiModel.Java
public class EmojiModel {
private int id;
private int price;
public String urlFile;
public EmojiModel(String urlFile) {
this.urlFile=urlFile;
}
public String getEmojiFile() {
return urlFile;
}
public void init(JSONDictionary data){
try{
urlFile = (String) data.get("urlFile");
id = Integer.parseInt((String) data.get("id"));
price = Integer.parseInt((String) data.get("price"));
}catch(Exception e){
e.printStackTrace();
}
}
}
obviously this line of code wont work :
imageView.setImageResource(Integer.parseInt((list.get(position)).urlFile));
instead of that just use glide or piccaso to load pics.
first add this line to your gradle file :
implementation 'com.github.bumptech.glide:glide:4.5.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.5.0'
then instead of above line ,just write :
Glide.with(context).load(list.get(position)).urlFile).into(imageView);
also the picaso library is pretty same
also change your adapter in this way :
public class EmojiAdapter extends BaseAdapter {
Context context;
ArrayList<EmojiModel> list = new ArrayList<>();
public EmojiAdapter(Context context,ArrayList<EmojiModel> list) {
super(context, R.layout.smiles_items_layout, list);
this.context = context;
this.list = list;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater o =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = o.inflate(R.layout.gifts_layout_2, parent , false);
ImageView imageView = (ImageView) v.findViewById(R.id.smile_image_view);
imageView.setImageResource(Integer.parseInt((list.get(position)).urlFile));
return v;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
Use Picasso in Adapter to show image
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater o =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = o.inflate(R.layout.gifts_layout_2, parent , false);
ImageView imageView = (ImageView) v.findViewById(R.id.smile_image_view);
Picasso.with(getApplicationContext()).load(list.get(position).getEmojiUrl()).into(imageView);
return v;
}
}
I'm new at android. and I want to load a new template which contains two button on a selected item of grid view object.
Is that possible.
I added a gridview to my project and by using base adapter a template was loaded to each item of gridview. But what I want is that when I clicked an item of gridview, I want to load a new template (layout) to the selected item.
THE PROBLEM WAS SOLVED, followings are the edited codes
Base Adapter
public class KategoriAdapter extends BaseAdapter{
private Context mContext;
private String[] categoryValues;
private Bitmap[] pictures;
//indicate that positon for new template
private int mNewTemplatePos = -1;
public KategoriAdapter(Context context, String[] categoryValues, Bitmap[] pictures) {
this.mContext = context;
this.categoryValues = categoryValues;
this.pictures = pictures;
}
//apply new template to positon
public void useNewTemplate(int pos) {
mNewTemplatePos =pos;
//notiy list that data has changed and the list will refresh ui itself.
notifyDataSetChanged();
}
#Override
public int getCount() {
return categoryValues.length;
}
#Override
public Object getItem(int possition) {
return null;
}
#Override
public long getItemId(int possition) {
return 0;
}
#Override
public View getView(int possition, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int posId = mNewTemplatePos;
if (convertView == null){
if (mNewTemplatePos ==possition){
convertView = getNewTemplate(inflater,possition);
}else {
convertView = getNormalTemplate(inflater,possition);
}
}else {
if (posId==possition){
convertView = getNewTemplate(inflater,possition);
}else{
convertView = getNormalTemplate(inflater,possition);
}
}
return convertView;
}
private View getNormalTemplate(LayoutInflater inflater, int possition) {
final View grid = inflater.inflate(R.layout.kategoriler_list_item, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
ImageView categoryPictures = (ImageView) grid.findViewById(R.id.grid_item_resim);
cName.setText(categoryValues[possition]);
categoryPictures.setImageBitmap(pictures[possition]);
return grid;
}
private View getNewTemplate(LayoutInflater inflater, int possition) {
final View grid = inflater.inflate(R.layout.kategori_secenek_template, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
cName.setText(categoryValues[possition]);
Button btn_nesne_tani = (Button) grid.findViewById(R.id.btn_nesneleri_taniyalim);
Button btn_cumle_kur = (Button) grid.findViewById(R.id.btn_cumle_kuralim);
btn_nesne_tani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"nesne",Toast.LENGTH_SHORT).show();
}
});
btn_cumle_kur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"cümle",Toast.LENGTH_SHORT).show();
}
});
return grid;
}
}
KategoriActivity.java
.....
final KategoriAdapter adapter = new KategoriAdapter(getApplicationContext(), mKategoriler, kategoriResimleri);
grid=(GridView)findViewById(R.id.gv_kategoriler);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.useNewTemplate(position);
Toast.makeText(getApplicationContext(), mKategoriler[position].toString(),Toast.LENGTH_SHORT).show();
}
});
}
I have rewrite your KategoriAdapter class:
public class KategoriAdapter extends BaseAdapter {
private Context mContext;
private final String[] categoryValues;
private final Bitmap[] pictures;
//indicate that positon in list are all use new template
private List<Integer> mNewTemplatePos;
public ImageView categoryPictures;
//indicate that this is normal template view
private final String NORMAL_TEMPLATE = "NORMAL_TEMPLATE";
//indicate that this is new template view
private final String NEW_TEMPLATE = "NEW_TEMPLATE";
public KategoriAdapter(Context context, String[] categoryValues, Bitmap[] pictures) {
this.mContext = context;
this.categoryValues = categoryValues;
this.pictures = pictures;
this.mNewTemplatePos = new ArrayList<>();
}
//apply new template to positon
public void useNewTemplate(int pos) {
mNewTemplatePos.add(pos);
//notiy list that data has changed and the list will refresh ui itself.
notifyDataSetChanged();
}
#Override
public int getCount() {
return categoryValues.length;
}
#Override
public Object getItem(int possition) {
return null;
}
#Override
public long getItemId(int possition) {
return 0;
}
#Override
public View getView(int possition, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if (mNewTemplatePos.contains(possition)) {
convertView = getNewTemplate(inflater, possition);
//use tag to indicate the type of the template
convertView.setTag(NEW_TEMPLATE);
} else {
convertView = getNormalTemplate(inflater, possition);
convertView.setTag(NORMAL_TEMPLATE);
}
} else {
switch ((String) convertView.getTag()) {
case NORMAL_TEMPLATE:
//convertView is the normal template view but you need a new template view in possition
if (mNewTemplatePos.contains(possition))
convertView = getNewTemplate(inflater, possition);
break;
case NEW_TEMPLATE:
//convertView is the new template view but you need a normal template view in possition
if (!mNewTemplatePos.contains(possition))
convertView = getNormalTemplate(inflater, possition);
break;
}
}
return convertView;
}
private View getNormalTemplate(LayoutInflater inflater, int possition) {
View grid = inflater.inflate(R.layout.kategoriler_list_item, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
categoryPictures = (ImageView) grid.findViewById(R.id.grid_item_resim);
cName.setText(categoryValues[possition]);
categoryPictures.setImageBitmap(pictures[possition]);
return grid;
}
private View getNewTemplate(LayoutInflater inflater, int possition) {
// TODO: 31/08/16 inflate you new template view layout here
return youNewTemplateView;
}
}
You should determine wether if current contentView is the right template type in getView() because contentView may be one of the new template in your list when it is not null.It is convenient to use tag to indicate the template type.
When to use useNewTemplate(position)?
Just apply the position that you need to use new template to useNewTemplate() and use it in your onItemClick() method.
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
useNewTemplate(position);
}
});
The current project I have includes a ListView with a Custom Adapter. However, I am now interested in adding multiple types of views to my ListView but after several attempts I have been unable to add the two sources of code together to successfully integrate them.
Article on ListView with multiple views: ListView Article for multiple views
The custom adapter in my current code retrieves the data from another class called getData which is referenced by "data".
Code from article (ListView with multiple views):
public class MultipleItemsList extends ListActivity {
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
for (int i = 1; i < 50; i++) {
mAdapter.addItem("item " + i);
if (i % 4 == 0) {
mAdapter.addSeparatorItem("separator " + i);
}
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList mData = new ArrayList();
private LayoutInflater mInflater;
private TreeSet mSeparatorsSet = new TreeSet();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
Current code (ListView with custom adapter):
FragmentA.java
package com.example.newsapp;
public class FragmentA extends Fragment{
getData data = getData.getMyData();
public Integer ArticleID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_a, container, false);
ListView listView = (ListView)V.findViewById(R.id.list)
CustomList adapter = new
CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.BitmapList.toArray(new Bitmap[data.BitmapList.size()]), data.ArticleID.toArray(new Integer[data.ArticleID.size()]));
listView.setAdapter(adapter);
listView.setOnItemClickListener(this); //Removed on click item event code.
return V;
}
CustomList.java
package com.example.newsapp;
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
return rowView;
}
}
Edit:
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
int viewType = getItemViewType(position);
View rowView = null;
switch(viewType) {
case 0:
LayoutInflater inflater = context.getLayoutInflater();
rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
case 1:
LayoutInflater inflater2 = context.getLayoutInflater();
rowView= inflater2.inflate(R.layout.single_row_loadmore, null, true);
}
return rowView;
}
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
}
First, a bit of an aside: you should create a class that encapsulates a headline, description, etc. and use an array/collection of those objects to back your adapter. It will be far easier than managing many disparate arrays of things, especially if one day you decide you need another attribute of an Article (its category, for example).
class Article {
int id;
String headline;
String description;
Bitmap picture;
}
With regard to your ListView, the magic happens in the methods getItemViewType() and getViewTypeCount(). In getViewTypeCount() you return the maximum number of row types -- the article you posted uses two row types and so returns 2. In getItemViewType() you return a value between zero and (viewTypeCount - 1) -- in the article, his implementation can return 0 or 1 because his viewTypeCount is 2.
How you decide which row type applies to each item is entirely up to you. If, for example, you wanted to simply alternate view types on every row, you can do this:
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
In other applications you would probably inspect the item at the given position to help you determine what should be returned in getItemViewtype().
The reason this functionality exists is that getView() provides a parameter (called convertView) that is a row which has been recycled. In order to give you an appropriate convertView, ListView needs to first know what row type it was. When you want to implement getView() for an adapter with multiple row types, it generally looks something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = getItemViewType(position);
switch(viewType) {
case 0:
return setUpOneViewType(position, convertView, parent);
case 1:
return setUpAnotherViewType(position, convertView, parent);
}
}
Note the cases for the switch statement correspond to the possible values that can be returned from getItemViewType(). These could be static final members.
I highly suggest watching The World of ListView. That video covers this topic as well as how to properly use convertView in your adapter implementation.