Not able to change fragment after clicking on recyclerview items - java

I have RecyclerView in my Main Activity. I want to change different fragments after clicking on different recyclerview Items. I try this by using position from onbindviewholder() but i am not able to change the fragment when i click on recyclerview items. I am not getting any error but at the same time nothing is happening onclick of recyclerview. Please check my code and tell me where i am wrong or which line of code i am missing.
RecyclerAdapter Code:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<NewModel> newModels;
Context context;
public RecyclerAdapter(ArrayList<NewModel>newModels, Context context){
this.newModels = newModels;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recy_layout, parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.imageView.setImageResource(newModels.get(position).getImg());
holder.textView.setText(newModels.get(position).getText());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position ==1){
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, new FirstFragment());
}
else if(position ==2){
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, new SecondFragment());
}
}
});
}
#Override
public int getItemCount() {
return newModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.cirlceimg);
textView = itemView.findViewById(R.id.text1);
}
}
}

you forgot to call commit()
do this:
(((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, new SecondFragment()).commit();
Fragment is not rendered until you call commit() on the transaction , because transaction use builder pattern and in builder pattern there is a method to say that i don't want to do anything else just create the object, normally these method are name create() , build(), and commit() in this case

You can handle the onClickListener from your activity using callback implementation with an interface.
Interface:
public interface OnItemClickListener {
void onItemClick(int position);
}
Add the listener to your adapter's constructor
ArrayList<NewModel> newModels;
Context context;
private final OnItemClickListener listener;
public RecyclerAdapter(ArrayList<NewModel>newModels, Context context, OnItemClickListener listener){
this.newModels = newModels;
this.context = context;
this.listener = listener;
}
In your onBindViewHolder set the clicklistener
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.imageView.setImageResource(newModels.get(position).getImg());
holder.textView.setText(newModels.get(position).getText());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position);
}
});
}
In your activity:
RecyclerAdapter rvAdapter = new RecyclerAdapter(newModels, this, new RecyclerAdapter.OnItemClickListener() {
#Override public void onItemClick(int item) {
if(position ==1){
getSupportFragmentManager().beginTransaction().replace(R.id.framelayout, new FirstFragment()).commit();;}
else if(position ==2){
getSupportFragmentManager().beginTransaction().replace(R.id.framelayout, new SecondFragment()).commit();;
}
}});
recycler.setAdapter(rvAdapter);

Inside onBindViewHolder
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position ==1){
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, new FirstFragment()).addToBackStack(null).commit();
}
else if(position ==2){
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, new SecondFragment()).addToBackStack(null).commit();
}
}
});
}
Hope this helps you.

Related

How to block particular Position in Adapter class ANDROID JAVA

I have an adapter class Where i Want to show a BLOCK USER dialog on particular position.
for example if i want to block position 1 of recyclerView .
So can any one help me porgrammatically?
Given below is the Code Of adapter Please check
I want to block user profile based on Recycler View position
if someone could help me in it please;
public class TableProfileAdapter extends RecyclerView.Adapter<TableProfileAdapter.MyViewHolder> {
Context context;
Activity getActivity;
List<TableProfile> profileUser;
OnRecItemClick onRecItemClick;
private boolean isScaleAnimationDone = false;
private boolean isTimerTextViewActionUpCalled = false;
public TableProfileAdapter(List<TableProfile> profileUser, Context context) {
this.profileUser = profileUser;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.profile_item, parent, false);
return new MyViewHolder(view, onRecItemClick);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TableProfile data = profileUser.get(position);
holder.tvUserName.setText(data.getProfileName());
Bitmap image = BitmapManager.byteToBitmap(data.getProfileImage());
holder.profilePic.setImageBitmap(image);
if (context instanceof AccessProfileManagementActivity) {
context.startActivity(new Intent(context,HomeActivity.class));
} else if (context instanceof ProfileManagement) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProfileDetailsActivity.class);
TableProfile model = profileUser.get(holder.getAdapterPosition());
intent.putExtra("DATA", model);
context.startActivity(intent);
notifyDataSetChanged();
((Activity) context).finish();
}
});
}
}
#Override
public int getItemCount() {
return profileUser.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView profilePic;
TextView tvUserName, birthday;
OnRecItemClick onRecItemClick;
RelativeLayout relativeLayout;
public MyViewHolder(#NonNull View itemView, OnRecItemClick onRecItemClick) {
super(itemView);
profilePic = itemView.findViewById(R.id.profileImage);
tvUserName = itemView.findViewById(R.id.userName);
relativeLayout = itemView.findViewById(R.id.relTop);
this.onRecItemClick = onRecItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onRecItemClick.onItemClick(getAdapterPosition());
}
}
public interface OnRecItemClick {
void onItemClick(int position);
}
}

How to send item position Adapter to fragment and fragment to activity

I have problem in my code i want first Adapter click item position in fragment and then this position want from fragment to MainActivity i have implement some design in my main_activity.xml so i want some data from model class by this position i have achieve Adapter click and successfully received in fragment but now i want this position fragment to MainActivty.java below my codes
My Adapter Class
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.ProductViewHolder> {
private Context mCtx;
private List<DataModal> productList;
private OnItemClickReturnData mListener;
public interface OnItemClickReturnData{
public void OnItemClick(int position);
}
public void setOnClickListener(OnItemClickReturnData listener)
{
mListener = listener;
}
public RvAdapter(Context mCtx, List<DataModal> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
#SuppressLint("InflateParams") View view = inflater.inflate(R.layout.song_handle_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ProductViewHolder holder, #SuppressLint("RecyclerView") final int position) {
final DataModal product = productList.get(position);
webUrl = "https://musicsongs.000webhostapp.com/";
Glide.with(mCtx)
.load(webUrl + product.getpics())
.into(holder.dp);
holder.pic.setText(product.getpic());
holder.pics.setText(product.getdp());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
if (mListener != null)
{
mListener.OnItemClick(position);
}
else {
Toast.makeText(mCtx, "mListeren is null" + mListener, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder{
TextView textViewTitle, textViewShortDesc;
ImageView imageView;
ProductViewHolder(View itemView) {
super(itemView);
pic= itemView.findViewById(R.id.pic);
pics = itemView.findViewById(R.id.pics);
dp = itemView.findViewById(R.id.dp);
}
}
}
My Fragment
public class MainActivityMusicFragment extends Fragment implements RvAdapter.OnItemClickReturnData {
}// i have achieve Adapter click in fragment by implements click method
#Override
public void OnItemClick(int position) {
Toast.makeText(getActivity(), "Posiotion OnClick in Adapter HAndle in Fragment" + position, Toast.LENGTH_SHORT).show();
}// i have received position in fragment but how can i send this position fragment to activity please help me
create a public method in you activity like
public void OnItemClickActivity(int position) {
Toast.makeText(this, "Posiotion OnClick in Activity" + position, Toast.LENGTH_SHORT).show();
}
and then in your fragment add this
#Override
public void OnItemClick(int position) {
((MainActivity) getActivity()).OnItemClickActivity(position)
Toast.makeText(getActivity(), "Posiotion OnClick in Adapter HAndle in Fragment" + position, Toast.LENGTH_SHORT).show();
}//
this is so simple do this ;-
#Override
public void OnItemClick(int position) {
// this is for your fragment
Bundle bundle = new Bundle();
Intent intent = new Intent(getActivity(), yourActivity.clss);
bundle.putString("position", position);
setArguments(bundle);
startActivity(intent);
Toast.makeText(getActivity(), "Posiotion OnClick in Adapter HAndle in Fragment" + position, Toast.LENGTH_SHORT).show();
}
// this is for your activity
String pos = getIntent().getStringExtra("position");
You have to implement callback in your activity
declare interface for call back :
interface OnMainActivityMusicFragmentListener{
void onItemSelected(int position);
}
Implement OnMainActivityMusicFragmentListener in your activity
class MainActivity extends AppCompactActivity implements OnMainActivityMusicFragmentListener{
----
}
Trigger your callback from Fragment
private OnMainActivityMusicFragmentListener listener:
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (OnMainActivityMusicFragmentListener) context;
}
// pass your position to activity
#Override
public void OnItemClick(int position) {
Toast.makeText(getActivity(), "Posiotion OnClick in Adapter HAndle in Fragment" + position, Toast.LENGTH_SHORT).show();
listener.onItemSelected(position);
}
For more information check this .

Onclick to open activity from adapter of fragment not working

I am trying to run some code I got from some online tutorial of writing a fragment with a recyclerview in it but I am experiencing some difficulty in opening an activity from the onclick event. My adapter is below
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.MyViewHolder> {
private final ArrayList<ItemModel> mArrayList;
private Context mcontext;
ItemAdapter(ArrayList<ItemModel> mArrayList) {
this.mArrayList = mArrayList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
mcontext = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Glide.with(mcontext).load(mArrayList.get(position).getImage()).into(holder.item_image);
holder.item_name.setText(mArrayList.get(position).getTitle());
holder.item_description.setText(mArrayList.get(position).getDescription());
holder.item_tags.setText(mArrayList.get(position).getTags());
Log.d("MyAdapter", "position: " + position);
}
#Override
public int getItemCount() {
return mArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final ImageView item_image;
private final TextView item_name;
private final TextView item_description;
private final TextView item_tags;
private final LinearLayout cardViewLayout;
MyViewHolder(View view) {
super(view);
item_image = view.findViewById(R.id.item_image);
item_name = view.findViewById(R.id.item_name);
item_description = view.findViewById(R.id.item_description);
item_tags = view.findViewById(R.id.item_tags);
cardViewLayout = view.findViewById(R.id.cardViewLayout);
cardViewLayout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(mcontext, ItemView.class);
mcontext.startActivity(intent);
}
}
}
When I run the code nothing happens when i click on a item and neither do I see any error in the logcat
Instead, try like this,
ItemAdapter(Context context, ArrayList<ItemModel> mArrayList) {
this.mArrayList = mArrayList;
this.mContext = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_item, parent, false);
return new MyViewHolder(view);
}
In your fragment, while setting adapter
ItemAdapter itemAdapter=new ItemAdapter(getActivity(),itemList);
You can have a listener sent from the fragment to adapter. Instead of trying to start an activity from the adapter, you can send it back to the fragment to open the activity.
1. Define an interface
public interface MyAdapterListener {
void openActivity(/*any values to be sent*/);
}
2. The fragment should implement MyAdapterListener
3. send the listener object to an adapter in a constructor
ItemAdapter(ArrayList<ItemModel> mArrayList, MyAdapterListener listener) {..
mListener = listener;
}
4. On Adapter - View Holder: in onClick() return to fragment
public void onClick(View view) {
mListener.openActivity(/*any values to be sent*/);
}
I was of the idea that on your application of the adapter in some activity you simply call the activity on the setOnItemClickListener of the adapter
private void loadItemsData() {
RecyclerView itemsRecyclerView = view.findViewById(R.id.posts_recycler_view);
itemsRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
itemsRecyclerView.setLayoutManager(layoutManager);
ItemAdapter myadapter = new ItemAdapter(new ArrayList<MyItem>(), getContext());
myadapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, PostItems items) {
ViewItem.passingIntent(getActivity(), items.postid);
}
});
itemsRecyclerView.setAdapter(ListAdapter );
}
then once done that you come to the receiver activity and make way to get the variables being passed on to it
public static void passingIntent(Activity activity, Integer postid){
Intent intent = new Intent(activity, ViewItem.class);
intent.putExtra(MY_ITEM, postid);
activity.startActivity(intent);
}
I have used this approach in one of my apps lately
Try setting your click listener in onBindViewHolder like below
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Glide.with(mcontext).load(mArrayList.get(position).getImage()).into(holder.item_image);
holder.item_name.setText(mArrayList.get(position).getTitle());
holder.item_description.setText(mArrayList.get(position).getDescription());
holder.item_tags.setText(mArrayList.get(position).getTags());
holder.setOnClickListener(this) // put this line
Log.d("MyAdapter", "position: " + position);
}
Then of course you will override onClick in adapter rather than viewholder

viewHolder.getAdapterPosition() in adapter return -1 position and it caused IndexOutOfBoundException

i try to implement best practice to handle onclick in adapter, but i got problem IndexOutOfBoundException when getAdapterPostition inside onCreateViewHolder, whats wrong with my code?
i already try to check but not solve yet.
public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private DataFrontVideo datas;
private Context context;
public VideoAdapter(DataFrontVideo datas, Context context) {
this.datas = datas;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_video,null);
final ViewHolder viewHolder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DataVideo video = datas.getContent().get(viewHolder.getAdapterPosition()); // ERROR HERE
Intent intent = new Intent(context,DetailActivity.class);
intent.putExtra("datas",video);
context.startActivity(intent);
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
DataVideo dataVideo = datas.getContent().get(position);
ViewHolder vh = (ViewHolder)viewHolder;
vh.tvTitle.setText(dataVideo.getJudul());
vh.tvArtis.setText(dataVideo.getAlias());
vh.tvPrice.setText((dataVideo.getPrice().equals("0")?"Gratis":dataVideo.getPrice()));
Glide.with(vh.img.getContext()).load(dataVideo.getThumb_pic()).into(vh.img);
}
#Override
public int getItemCount() {
return (datas == null)? 0 : datas.getContent().size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
private TextView tvTitle,tvArtis,tvPrice;
public ViewHolder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imgVideo);
tvArtis = itemView.findViewById(R.id.tvartis);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvPrice = itemView.findViewById(R.id.tvPrice);
}
}
}
it should not return -1
Inside your ViewHolder you need to apply the setOnClickListener and get the item position on click by using the getAdapterPosition() like below
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
private TextView tvTitle,tvArtis,tvPrice;
public ViewHolder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imgVideo);
tvArtis = itemView.findViewById(R.id.tvartis);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvPrice = itemView.findViewById(R.id.tvPrice);
YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext,"Position==>> "+getAdapterPosition(),Toast.LENGTH_LONG).show();
DataVideo video = datas.getContent().get(viewHolder.getAdapterPosition()); // ERROR HERE
Intent intent = new Intent(context,DetailActivity.class);
intent.putExtra("datas",video);
context.startActivity(intent);
}
});
}
}
Actually, the problem just because you are registering click listener in your onCreateViewHolder which is wrong you need to register on Click listener in your onBindViewHolder like bellow
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
DataVideo dataVideo = datas.getContent().get(position);
ViewHolder vh = (ViewHolder)viewHolder;
vh.tvTitle.setText(dataVideo.getJudul());
vh.tvArtis.setText(dataVideo.getAlias());
vh.tvPrice.setText((dataVideo.getPrice().equals("0")?"Gratis":dataVideo.getPrice()));
Glide.with(vh.img.getContext()).load(dataVideo.getThumb_pic()).into(vh.img);
vh.parentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,DetailActivity.class);
intent.putExtra("datas",dataVideo);
context.startActivity(intent);
}
});
}
Move your click in onBindViewHolder .Here it will work for title click ,if you want all click make viewholder complete layout and implement click listener
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
DataVideo dataVideo = datas.getContent().get(position);
ViewHolder vh = (ViewHolder)viewHolder;
vh.tvTitle.setText(dataVideo.getJudul());
vh.tvArtis.setText(dataVideo.getAlias());
vh.tvPrice.setText((dataVideo.getPrice().equals("0")?"Gratis":dataVideo.getPrice()));
Glide.with(vh.img.getContext()).load(dataVideo.getThumb_pic()).into(vh.img);
vh.tvTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,DetailActivity.class);
intent.putExtra("datas",dataVideo );
context.startActivity(intent);
}
});
}

How to Implemet onClick listener insidie Recycleview to open different activities

I'm using Horizontal Recycleview to show the icon in my app. It cotains one Recycle view and one Mainactivity Class.
I'm trying to use the onClick listener method inside the adapter class but to my surprise it is not working yet all and also don't recognize intent and give cannot resolve intent symbol. so I used toast message instead but also app compile sucessfully but nothing happens.
Here is my Recycle view class
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
return new ReyclerViewHolder(item);
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
private View.OnClickListener Click=new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(getAdapterPosition())
{
case 1:
Toast.makeText(context, "No data available", Toast.LENGTH_SHORT).show();
}
}
};
}
}
and my Mainactivity class is
public class MainActivity extends AppCompatActivity {
private ArrayList<Item> items;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
createApps();
SnapHelper snapHelper = new GravitySnapHelper(Gravity.BOTTOM);
snapHelper.attachToRecyclerView(recyclerView);
// HORIZONTAL for Gravity START/END and VERTICAL for TOP/BOTTOM
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setHasFixedSize(true);
SnapRecyclerAdapter adapter = new SnapRecyclerAdapter(this, items);
recyclerView.setAdapter(adapter);
}
private void createApps() {
items = new ArrayList<>();
items.add(new Item("Google+", R.drawable.google_plus));
items.add(new Item("Facebook", R.drawable.facebook));
items.add(new Item("LinkedIn", R.drawable.linkedin));
items.add(new Item("Youtube", R.drawable.youtube));
items.add(new Item("Instagram", R.drawable.instagram));
items.add(new Item("Skype", R.drawable.skype));
items.add(new Item("Twitter", R.drawable.twitter));
items.add(new Item("Wikipedia", R.drawable.wikipedia));
items.add(new Item("Whats app", R.drawable.what_apps));
items.add(new Item("Pokemon Go", R.drawable.pokemon_go));
}
}
Your implementation setOnClickListener is not correct. You should set it for each view in RecylerView and inside that you can write your code to start an activity or show a toast, etc.
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
ReyclerViewHolder holder = new ReyclerViewHolder(item)
item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, items.get(holder.getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
// TODO: You can start an activity by using Intent as well.
}
});
return holder;
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
}
}
You want the click listener on the whole itemView? Here is an example:
//Implement View.OnClickListener
class ReyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
// Set the onClickListener
v.setOnClickListener(this)
}
#Override
public void onClick(View v) {
// if (getAdapterPosition() != RecyclerView.NO_POSITION) {
Context context = v.getContext();
Intent intent = new Intent(context, aActivityClass.class);
intent.putExtra(extraKey, extraValue);
context.startActivity(intent)
// }
};
}
Do you set the click listener on a View ? Something like image.setOnClickListener(Click) ? By the way, variables should start with lowercase
you need to pass the view from adapter by using onclickListner and make and internface in adapter
this is where we are passing the view in adapter :
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
Interface for adapter onclick and activity:
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
Define Interface as glocbal object in adapter:
private OnItemClick onItemClick;
Consider this example for adapter:
public class PartnerBankAdapter extends RecyclerView.Adapter<PartnerBankAdapter.myholder> {
public Context mContext;
ArrayList<String> bankname;
ArrayList<Integer> iconlist;
private OnItemClick onItemClick;
public PartnerBankAdapter(Context mContext, ArrayList<String> banklist,ArrayList<Integer> iconlist)
{
this.mContext = mContext;
this.bankname=banklist;
this.iconlist=iconlist;
}
#Override
public myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bank_list_adpater,parent,false);
return new myholder(view);
}
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
holder.txt.setText(bankname.get(position));
holder.image.setImageResource(iconlist.get(position));
holder.txtacc.setText(bankname.get(position));
}
#Override
public int getItemCount() {
return bankname.size();
}
public static class myholder extends RecyclerView.ViewHolder {
TextView txt,txtacc;
ImageView image;
LinearLayout parent;
public myholder(View itemView) {
super(itemView);
txt= (TextView) itemView.findViewById(R.id.txbank);
image=(ImageView) itemView.findViewById(R.id.imagebank);
parent=(LinearLayout) itemView.findViewById(R.id.parent);
txtacc=(TextView) itemView.findViewById(R.id.txbankacc);
}
}
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
}
and then just use onclick in your activity on recyclerview
consider code below for onclick in activity :
partnerBankAdapter.clickItem(new PartnerBankAdapter.OnItemClick() {
#Override
public void click(int postion, View view) {
}
});

Categories