javaandroidandroid-studiogridviewcustom-adapter

Changing Layout file on custom adapter depending on activity (Android)


I want to change the layout file that is used depending on which activity is running. I have two activities which need a grid view and both are very similar so I thought I should be able to use the same adapter. The only thing that needs changing is the layout file.

This is my custom adapter:

package com.example.placesofinterest;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

public class GridAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Bitmap> img;

    public GridAdapter(Context c, ArrayList<Bitmap> img){
        this.context = c;
        this.img = img;
    }
    @Override
    public int getCount() {
        return img.size();
    }

    @Override
    public Object getItem(int position) {
        return img.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.places_layout, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(convertView);
            convertView.setTag(myViewHolder);
        }
        MyViewHolder myViewHolder = (MyViewHolder)convertView.getTag();
        myViewHolder.img.setImageBitmap(img.get(position));

        return convertView;
    }

    public class MyViewHolder {
        public ImageView img;

        public MyViewHolder(View view) {
            img = view.findViewById(R.id.imageView);
        }
    }
}

I was thinking in getView whether there was anyway to determine whether MainActivity1 is running or MainActivity2 is running and using that, I could change the layout file.

Ie:

if (convertView == null) {
            inflater = LayoutInflater.from(context);
            if (Activity = MainActivity )
                convertView = inflater.inflate(R.layout.row_layout, parent, false);
            else if (Activity = MainActivity2)
                convertView = inflater.inflate(R.layout.row_layout2, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(convertView);
            convertView.setTag(myViewHolder);
        }

Solution

  • Did you try to do that ?

    if (context instanceof MainActivity) {
      // some code
    } else if (context instanceof MainActivity2){
      // handle service case
    }
    

    I'm not sure it will work, but try and tell me :D