Skip to content Skip to sidebar Skip to footer

Imageadapter Cannot Be Applied To Fragment Class

I've followed the documentation on how to use GridView and had the same issue as this guy ImageAdapter cannot be applied to a Fragment Class The code in my Fragment Class is as fol

Solution 1:

You need to have a constructor in your ImageAdapter class which will take the context as a parameter.

And you have to set the background of the image based on the adapter position as well.

Here's the modified adapter class.

publicclassImageAdapterextendsBaseAdapter {

    private Context mcontext;

    publicImageAdapter(Context context) {
        mContext = context;
    }

    @OverridepublicintgetCount() {
        return mthumbids.length;
    }

    @Overridepublic Object getItem(int position) {
        returnnull;
    }

    @OverridepubliclonggetItemId(int position) {
        return0;
    }

    @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = newImageView(mcontext);
            imageView.setLayoutParams(newGridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);

            // Add the following to load the image
            imageView.setBackground(ContextCompat.getDrawable(context, mthumbids[position]));
        }
        else  {
            imageView = (ImageView)convertView;
        }

        return imageView;
    }

    private Integer[] mthumbids =
            {
              R.drawable.img1, R.drawable.img2,
              R.drawable.img3, R.drawable.img4,
              R.drawable.img5, R.drawable.img6
            };
}

Solution 2:

You can also get the context from the parent in getView(). Then you don't have to pass and store the context. So your getView looks like this:

@Overridepublic View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        Contextcontext= parent.getContext(); // <-- add this line
        imageView = newImageView(context); // use the context from the parent
        imageView.setLayoutParams(newGridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    }
    else  {
        imageView = (ImageView)convertView;
    }

    return imageView;
}

Solution 3:

Missing constructor with argument context for ImageAdapter. Only empty constructor will be created automatically you should write constructors with specific argument values.

publicImageAdapter(Context context){

mContext = context; }

Solution 4:

Add this code in ImageAdapter class.

publicImageAdapter(Context context) {
    super();
    mContext = context;
}

Post a Comment for "Imageadapter Cannot Be Applied To Fragment Class"