Skip to content
Advertisement

Getting the Activity inside Adapter in Android

I am trying to access the activity on which my Imageview is, so I can use the URL of an Image of type SVG and display it to the user using the GlideToVectorYou library.

GlideToVectorYou.justLoadImage(activity, IMAGE_URI, targetImageView)

But when I try to get access to the activity using R.layout.activityname, a syntax error appears. this is the code that I’m using

 Uri myurl = Uri.parse(match.getFlag());
 GlideToVectorYou.justLoadImage(R.layout.item_basketball, myurl, iv_location);

Thank you!

Advertisement

Answer

R.layout.item_basketball is just an integer ID for your activity layout – not the activity instance itself. If you want the activity in your adapter you would need to pass it in when you construct the adapter and save it as a class member (example below), or check if your adapter base class already can provide it via getActivity() or getContext() or a similar method.

class MyAdapter(private val activity: Activity) : BaseAdapter() {
    fun someMethod() {
        // then you can access "activity" in your adapter methods
        GlideToVectorYou.justLoadImage(activity, IMAGE_URI, targetImageView)
    }
}

and when you create it in your Activity, you would just do something like this

val adapter = MyAdapter(this)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement