0

Question:

How do we pass a OnLongClickListener into an adapter when setting it in the activity?

Adapter's constructor:

public Activity mcontext;
public View.OnLongClickListener LongClicking;

public SubjectsAdapter(Activity context, View.OnLongClickListener longClick) {
    this.mcontext = context;
    this.LongClicking = longClick;
}

In the activity:

adapter = new SubjectsAdapter(this, /*A OnLongClickListener here */ );

I know this is probably a dense question, I'm relatively new to android

John Sardinha
  • 3,566
  • 6
  • 25
  • 55

1 Answers1

1

Basically you can pass it as an anonymous class

adapter = new SubjectsAdapter(this, new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            //do your stuff
        }
    } );

But how do you register this callback for a particular view? I'd suggest to register it for the view, which is interested in this callback with setOnLongClickListener instead of passing it to the adapter (but it depends on your app).

yourview.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            //do your stuff
        }
    });
Luke
  • 2,539
  • 2
  • 23
  • 40
  • woudn't that first option be the same as setting the OnLongCLickListener in the adapter's ViewHolder? (I'm using a RecyclerView) – John Sardinha Apr 23 '16 at 19:07
  • Yes, you can do that. You can also implement `View.OnLongClickListener` in your particular `RecyclerView.ViewHolder`. See this [this answer](http://stackoverflow.com/questions/30078344/handle-on-item-long-click-on-recycler-view) or this [this](http://stackoverflow.com/questions/27945078/onlongitemclick-in-recyclerview/27945635#27945635) – Luke Apr 23 '16 at 19:16