How to avoid duplication of adapter code I create applications where there are 2 listLiew. Here is the code of the 1st adapter. The 2nd adapter is exactly the same, but you need to add several View elements. How to make one adapter fit both.

public class AdsAdapter extends BaseAdapter {

private List<Ads> list; private LayoutInflater layoutInflater; public AdsAdapter(Context context, List<Ads> list) { this.list = list; layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub **View view = convertView; if (view == null) { view = layoutInflater.inflate(R.layout.list_item_layout, parent, false); } TextView textViewAds = (TextView) view.findViewById(R.id.textViewAds); textViewAds.setText(getAds(position).getAddsText().toString()); ImageView imageViewPc = (ImageView) view.findViewById(R.id.imagePic); Bitmap b1 = BitmapFactory.decodeByteArray(getAds(position).getPhoto(), 0, getAds(position).getPhoto().length); imageViewPc.setImageBitmap(b1);** return view; } private Ads getAds(int position) { return (Ads) getItem(position); } 

}

    3 answers 3

    There are three available methods:

    • in the old manner (possible, but not recommended). Add a special boolean (integer type) field to the adapter, which will indicate exactly what behavior is needed. If / switch is added in the right places. If two adapters differ in a single view in getView, this method can be justified.

    • delegation. We make two adapters and one class that stores common functionality. In adapters, we simply forward calls to the class, different methods are implemented in place. Pros: easier to test, fashionable.

    • done as in the previous case, only the class turns into an adapter. Perhaps with abstract methods. Two adapters with the necessary functionality are inherited from it. Pros: with the right approach, you can get by with only two adapters, inheriting one from the other and not making three classes.

      Create the 2nd adapter class that inherits from the first one and in it override getItem()

        You have several tools for this. At least composition and inheritance.

        The logic for generating the view can always be put into a separate class, an instance of which is passed to your adapter at the creation stage (see the Strategy template), in this case you will have only one adapter class.