Home > other >  Getting the Activity inside Adapter in Android
Getting the Activity inside Adapter in Android

Time:12-20

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!

CodePudding user response:

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)

CodePudding user response:

You need a activity reference. R.layout.somethinghere is the layout reference.

On your adapter constructor add a activity parameter and use it inside the adapter.

If you call adapter constructor from an activity, just pass "this" as parameter. If call from a fragment, use "requireActivity" (if using kotlin) or analogous method (getActivity, for example) if using Java

  • Related