I want to add startActivity()
to my onClick
listeners in my CustomAdapter class.
CustomAdapter.java
:
import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import static androidx.core.content.ContextCompat.startActivity; public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> { private List<String> data; public CustomAdapter (List<String> data){ this.data = data; } @Override public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View rowItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view, parent, false); return new ViewHolder(rowItem); } @Override public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) { holder.textView.setText(this.data.get(position)); } @Override public int getItemCount() { return this.data.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView textView; public ViewHolder(View view) { super(view); view.setOnClickListener(this); this.textView = view.findViewById(R.id.textview); } @Override public void onClick(View view) { startActivity(new Intent(CustomAdapter.this, LoginActivity.class)); } } }
The problem is I’m getting the following error in my IDE:
Cannot resolve constructor 'Intent(com.kenadams.app.CustomAdapter, java.lang.Class<com.kenadams.app.LoginActivity>)'
Initially , I thought this was happening because my CustomAdapter
class was static
. So, I made it non-static. But, the problem still persists. Pls guide me on making this intent work.
Advertisement
Answer
In you customer adapter class you need to get context using constructor.
private Context mcon;
and in constructor->
public CustomAdapter (Context _mcon, List<String> data){ this.mcon = _mcon; this.data = data; }
and then in onClickListener->
@Override public void onClick(View view) { mcon.startActivity(new Intent(mcon, LoginActivity.class)); }