I made my adapter for the listview from the example, but such a question arose: the list consists of 6 elements, each of the elements has a fixed set of resources in accordance with the DataAdapter class, in the first one there should be 6 resources in the second 5 and in the third already 4, is it possible somehow cancel this fix?

Instead of missing resources, I added blank lines.

list.add(new DataAdapter(R.string.N5A, R.string.Pr1, R.string.N2, R.string.Nm,R.drawable.foot,R.drawable.bus)); list.add(new DataAdapter(R.string.N14,R.string.p,R.string.p, R.string.Nm1,R.drawable.c,R.drawable.c)); list.add(new DataAdapter(R.string.N1,R.string.Pr1, R.string.N2,R.string.Nm2,R.drawable.foot, R.drawable.bus)); list.add(new DataAdapter(R.string.N11,R.string.p, R.string.p, R.string.Nm3,R.drawable.c, R.drawable.c)); list.add(new DataAdapter(R.string.N1B,R.string.Pr1, R.string.p, R.string.Nm4, R.drawable.foot,R.drawable.bus)); list.add(new DataAdapter(R.string.N16A, R.string.Pr1, R.string.N2, R.string.Nm5, R.drawable.foot, R.drawable.bus)); 

DataAdapter Code

 public class DataAdapter { private int flagID; public int imgID; private int nameID; private int nameID2; private int nameID3; private int abbreviationID; public DataAdapter(int _nameID,int _nameID3, int _nameID2, int _abbreviationID,int _imgID, int _flagID){ nameID = _nameID; nameID3 = _nameID3; nameID2 = _nameID2; abbreviationID = _abbreviationID; imgID = _imgID; flagID = _flagID; } public int getNameID3(){ return nameID3; } public int getNameID(){ return nameID; } public int getNameID2(){ return nameID2; } public int getAbbreviationID() { return abbreviationID; } public int getFlagID(){ return flagID; } public int getImgID(){ return imgID; } } 

Class MyListAdapter if needed

 public class MyListAdapter extends BaseAdapter{ /* * Создаем объекты для отображения внешнего вида элемента * и объекта списка, с которым будет производиться работа */ private LayoutInflater LInflater; private ArrayList<DataAdapter> ls; /* * Конструктор класса. В данном случае лишь транслируется лист с данными * в лист адаптера, с которым будет производиться непосредственная работа */ public MyListAdapter(Context context, ArrayList<DataAdapter> data){ ls = data; LInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /* * Далее идут стандартные методы родительского класса BaseAdapter. * Внимательно ознакомьтесь с отличиями методов в уроке и методов, * которые автоматически создает Android Studio. * Данные методы должны работать непосредственно с используемым нами ArrayList * и структурой данных, формируемой классом Dataadapter */ @Override public int getCount() { return ls.size(); } @Override public DataAdapter getItem(int position) { return ls.get(position); } @Override public long getItemId(int position) { return position; } /* * Метод, в котором формируется внешний вид элементов с его наполнением */ @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; /* * В том случае, если вид элемента не создан, производится его создание * с помощью ViewHolder и тегирование данного элемента конкретным holder объектом */ if ( v == null){ holder = new ViewHolder(); v = LInflater.inflate(R.layout.layout_test, parent, false); holder.im = (ImageView) v.findViewById(R.id.imageView3); holder.img1 = (ImageView) v.findViewById(R.id.img1); holder.name = (TextView) v.findViewById(R.id.m1); holder.name3 = ((TextView) v.findViewById(R.id.m2)); holder.name2 = ((TextView) v.findViewById(R.id.m3)); holder.name4 = ((TextView) v.findViewById(R.id.textView2)); v.setTag(holder); } /* * После того, как все элементы определены, производится соотнесение * внешнего вида, данных и конкретной позиции в ListView. * После чего из ArrayList забираются данные для элемента ListView и * передаются во внешний вид элемента */ holder = (ViewHolder) v.getTag(); DataAdapter dataAdapter = getData(position); holder.im.setImageResource(dataAdapter.getFlagID()); holder.img1.setImageResource(dataAdapter.getImgID()); holder.name.setText(v.getResources().getString(dataAdapter.getNameID())); holder.name3.setText(v.getResources().getString(dataAdapter.getAbbreviationID())); holder.name4.setText(v.getResources().getString(dataAdapter.getNameID3())); holder.name2.setText(v.getResources().getString(dataAdapter.getNameID2())); return v; } /* * Метод, который забирает объект из ArrayList для дальнейшей работы с ним * и передачи его данных в элемент ListView */ DataAdapter getData(int position){ return (getItem(position)); } /* * Данная структура данных необходима для того, чтобы при пролистывании * большого списка не возникало артефактов и перескакивания данных с одной позиции ListView * на другую, что достигается тегированием каждого элемента ListView */ private static class ViewHolder { private ImageView im,img1; private TextView name, name2,name3,name4; } } 
  • one
    Not in the subject, but I advise you to name variables and other entities meaningfully, because you can easily get confused in what you have. The DataAdapter class is supposed to be an adapter, but it’s just the data from the model. - post_zeew
  • And on the topic: you can create some base class in which there will be three resources and inherit from it other classes with more resources. Or store resources in a class in a collection. Different ways can be done. - post_zeew
  • Complicated complicated ... - Grohovac
  • How much do you program in general and how much in Java? - post_zeew
  • It is not clear that you want to cancel. So that during initialization of the new DataAdapter() only the required number of parameters is specified? Or so that the cells in the ListView do not display items that are not in the DataAdapter ? - eugeneek

1 answer 1

Well, as you say, try for example to use "constructor overload"

 public DataAdapter(int _nameID,int _nameID3, int _nameID2, int _abbreviationID,int _imgID, int _flagID){ nameID = _nameID; nameID3 = _nameID3; nameID2 = _nameID2; abbreviationID = _abbreviationID; imgID = _imgID; flagID = _flagID; } public DataAdapter(int _nameID,int _nameID3, int _nameID2){ nameID = _nameID; nameID3 = _nameID3; nameID2 = _nameID2; } 

You can also use a variable number of elements - but there is a drawback - you need to strictly observe the position and check for their presence.

 public DataAdapter(int... ids){ nameID = ids[0]; nameID2 = ids[1]; nameID3 = ids[2]; abbreviationID = ids[3]; imgID = ids[4]; flagID = ids[5]; } 

And you can also make an empty constructor, initialize your object.

and set only the necessary parameters via set

 DataAdapter data = new DataAdapter(); data.setflagID(flagId); 

I brought only three, there are still at least 2 options. But I think you and this will be enough. Each method has its own advantages and disadvantages, that will suit you in this place, it's up to you to decide.