Reputation: 83
I'm having trouble with getActivity() in Activity. It says can't resolve method getActivity(). I'm using it to make onClick in recyclerView.
Here is my code
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this));
What should I change getActivity with? Thanks in advance
Upvotes: 3
Views: 10192
Reputation: 1551
All of the mentioned answers are correct. However, sometimes 'this' can't referenced as your Activity ,mostly when we try to pass it from inside one of callback methods like :
view.setOnClickListener(v->showToast(this));
In such cases ,pass the activity using the whole name of the class like this :
view.setOnClickListener(v->showToast(Sample.this));
Upvotes: 0
Reputation: 547
You can pass parameters like this:
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView));
Or for detail information you can refer this bolg :- Android - RecyclerView: Implementing single.
Upvotes: 0
Reputation: 83
I forgot to implements the recyclerclicklistener. After I implements the method and change
getActivity
to
this
it worked fine
extends AppCompatActivity implements RecyclerItemClickListener.OnItemClickListener
Upvotes: 1
Reputation: 819
You have declared your code inside of an Activity
. Therefore you can simply use this
to reference the Activity
you are in.
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, this));
Upvotes: 3
Reputation: 2795
change it to
this
this
is a reference to the class your in, like MainActivity.this
Upvotes: 1