Rishabh Rishabh - 10 days ago 7
Android Question

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

I have an activity which implements OntouchListener defined within it

@Override
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);
imageView.setImageResource(R.drawable.img1);
imageView.setOnTouchListener(this);


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);
imageView.setImageResource(R.drawable.img2);
//what should go into this line:
imageView.setOnTouchListener(mainActivity);
}
}

Answer

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:

    imageView.setOnTouchListener((OnTouchListener)mainActivity);
    
Comments