Rishabh Rishabh - 1 year ago 82
Android Question

How to set OnTouchListener to a view defined externally for an activity?

I have an activity which implements OntouchListener defined within it

public boolean onTouch(final View view, final MotionEvent event) {return true;}

for views which are defined inside the activity class I use

int resID = getResources().getIdentifier(resource, "id", "main.com.pack");
imageView = (ImageView) findViewById(resID);

The above code works pretty well for all events.
though for functions which are defined in other classes where I am passing my activity where other views are created I am not able to assign the OntouchListener from the activity which I am passing to the function.

public class ViewImageSetter {
ImageView imageView;
public void setViews(Context context, Activity mainActivity) {
int resID = context.getResources().getIdentifier(resource, "id", "main.com.pack");
imageView = (ImageView) mainActivity.findViewById(resID);
//what should go into this line:

Answer Source

You have different options to do that:

  • You set the Activity type of your setViews() method to the actual Activity type that implements the OnTouchListener: (MainActivity for example)

    public void setViews(Context context, MainActivity mainActivity) { ...
  • You pass an OnTouchListener object to your setViews() method instead of an Activity:

    public void setViews(Context context, OnTouchListener mainActivity) { ...

    Note that you cannot use specific Activity methods like findViewById() in this case anymore.

  • You assume that your Activity always implements the OnTouchListener interface, so you simply cast it to one:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download