How can I get view pager data in my activity android java - java

How can I get view pager data in my activity android java
i create image slider using viewpager i want to get current viewpager details in my activity
this is my activity i access view pager and set data
ViewPager2 locationViewPager = findViewById(R.id.locationViewPager);
ImageView next = findViewById(R.id.next);
ImageView back = findViewById(R.id.back);
genres = findViewById(R.id.textView1);
source = findViewById(R.id.textView2);
List<TravelLocation> travelLocations = new ArrayList<>();
for (int i=0;i<=1000;i++){
TravelLocation travelLocationMV = new TravelLocation();
travelLocationMV.imageUrl = R.drawable.cardimage;
travelLocationMV.genres = "Thriller";
travelLocationMV.source = "Netflix";
travelLocations.add(travelLocationMV);
}
TravelLocationAdapter travelLocationAdapter = new TravelLocationAdapter(travelLocations);
locationViewPager.setAdapter(travelLocationAdapter);
locationViewPager.setClipToPadding(false);
locationViewPager.setClipChildren(false);
locationViewPager.setOffscreenPageLimit(3);
locationViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
compositePageTransformer.addTransformer(new MarginPageTransformer(40));
compositePageTransformer.addTransformer((page, position) -> {
float r = 1 - Math.abs(position);
page.setScaleY(0.90f + r * 0.04f);
});
locationViewPager.setPageTransformer(compositePageTransformer);
this is my adapter
class TravelLocationAdapter extends RecyclerView.Adapter<TravelLocationAdapter.TravelLocationViewHolder> {
private List<TravelLocation> travelLocations;
public TravelLocationAdapter(List<TravelLocation> travelLocations) {
this.travelLocations = travelLocations;
}
#NonNull
#Override
public TravelLocationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new TravelLocationViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardlayout,
parent, false
)
);
}
#Override
public void onBindViewHolder(#NonNull TravelLocationViewHolder holder, int position) {
holder.setLocationData(travelLocations.get(position));
holder.kbvLocation.setOnClickListener(view -> {
});
}
#Override
public int getItemCount() {
return travelLocations.size();
}
static class TravelLocationViewHolder extends RecyclerView.ViewHolder {
private ImageView kbvLocation;
TravelLocationViewHolder(#NonNull View itemView) {
super(itemView);
kbvLocation = itemView.findViewById(R.id.kbvLocation);
}
void setLocationData(TravelLocation travelLocation) {
Picasso.get().load(travelLocation.imageUrl).into(kbvLocation);
}
}
this is my data class
class TravelLocation {
public String imageUrl;
public String genres,source; }
i want to access other 2 field in my activity
i wan to set this filed in activity

use interface to access recyclerView data.check this answer how to create interface :
How to create a interface in main activity and pass the data from adapter to main activity through the interface?

Related

Display the passing data between two fragments in recyclerView

I have data taken from an API, I have added a button that when pressed will move (title, image, and some data from FRAGMENT to other FRAGMENT), this data is taken from RECYCLERLVIEW and will be shown in RECYCLERVIEW. But when the button is pressed, nothing happens and the data is not transmitted.
The project link if you want to take a deeper look "Mox Project"
Here's the first adapter that I send data from
--- CNNAdapter ---
private List<Item> items = null;
#SuppressLint("NotifyDataSetChanged")
public void setCNNList(List<Item> items) {
this.items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new NewsViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_news,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Item News = items.get(position);
((NewsViewHolder) holder).setData(News);
((NewsViewHolder) holder).sendData(News);
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class NewsViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView description;
private final TextView source;
private final TextView author;
private final Button sendDataButton;
private final Activity activity = new Activity();
NewsViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_news);
title = itemView.findViewById(R.id.title_news);
description = itemView.findViewById(R.id.description_news);
source = itemView.findViewById(R.id.source_news);
author = itemView.findViewById(R.id.author_name_news);
sendDataButton = itemView.findViewById(R.id.button_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData(Item news) {
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread(() -> {
Glide.with(itemView.getContext())
.load((Objects.requireNonNull(news.getEnclosure())).getLink())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(news.getTitle());
description.setText(Html.fromHtml(Objects.requireNonNull(news.getDescription()).replaceAll("(<(/)img>)|(<img.+?>)", ""), Html.FROM_HTML_MODE_COMPACT));
source.setText(R.string.cnn);
author.setText(R.string.author);
}
void sendData(Item news) {
sendDataButton.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("title", news.getTitle());
bundle.putString("image", Objects.requireNonNull(news.getEnclosure()).getLink());
bundle.putString("source", "CNN");
bundle.putString("author", "CNN editor's");
bundle.putString("link", news.getLink());
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
});
}
}
Here's the second adapter that I get the data and set it
--- FavoriteAdapter ---
public class FavoriteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Item> items = new ArrayList<>();;
private Context context;
#SuppressLint("NotifyDataSetChanged")
public void setFavoriteList(ArrayList<Item> items, Context context) {
this.items = items;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new FavoriteViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_save,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((FavoriteViewHolder) holder).setData();
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class FavoriteViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView source;
private final TextView author;
private final Activity activity = new Activity();
FavoriteViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_article_save);
title = itemView.findViewById(R.id.title_article_save);
source = itemView.findViewById(R.id.source_article_save);
author = itemView.findViewById(R.id.author_name_article_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData() {
FavouriteFragment favouriteFragment = new FavouriteFragment();
Bundle bundle = favouriteFragment.getArguments();
String getTitle = bundle.getString("title");
String getImage = bundle.getString("image");
String getSource = bundle.getString("source");
String getAuthor = bundle.getString("author");
String getLink = bundle.getString("link");
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread (() -> {
Glide.with(itemView.getContext())
.load((getImage))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(getTitle);
source.setText(getSource);
author.setText(getAuthor);
}
}
My fragment that I display the data using recyclerview
--- FavouriteFragment ---
public class FavouriteFragment extends Fragment {
private FragmentFavouriteBinding binding;
ArrayList<Item> arrayList = new ArrayList<>();;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentFavouriteBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
requireActivity().setTitle("");
initializeViews();
return view;
}
private void initializeViews() {
FavoriteAdapter adapter = new FavoriteAdapter();
binding.recyclerViewFavorites.setLayoutManager(new LinearLayoutManager(requireContext()));
binding.recyclerViewFavorites.setHasFixedSize(true);
binding.recyclerViewFavorites.setAdapter(adapter);
adapter.setFavoriteList(arrayList,getContext());
}
The project link if you want to take a deeper look "Mox Project"
Thank you for your help.
Possible problems or issues that may cause the button not to show the passed data.
remember a view will only display when it gets data.
Here are some resources that might help:
Passing Data between Fragments on Android Using ViewModel
Managing UI-related data in activity lifecycles
https://heartbeat.fritz.ai/passing-data-between-fragments-on-android-using-viewmodel-d47fa6773f9c
How to pass values between Fragments
https://android-developers.googleblog.com/2011/02/android-30-fragments-api.html
The displaying of Fragments is managed by FragmentManager. You must pass an instance of FragmentManager to CNNAdapter as follows:
public class CNNAdapter extends RecyclerView.Adapter<CNNAdapter.NewsViewHolder> {
private final FragmentManager mFragmentManager;
public CNNAdapter(FragmentManager mFragmentManager) {
this.mFragmentManager = mFragmentManager;
}
public void addData(List<> items) {
list.addAll(items);
notifyDataSetChanged();
}
}
And then you display the fragment as follows:
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
mFragmentManager.beginTransaction().replace(R.id.fragment_container,favouriteFragment).commit();
R.id.fragment_container is the view ID of the container in the layout xml of the activity that hosts the fragment. The container is usually a FrameLayout.
And then you instantiate CNNAdapter in the Fragment like this:
CNNAdapter cnnAdapter = new CNNAdapter(getFragmentManager());

How to get the item position in a ListView and GridView outside the adapter?

I'm trying to get a View position through his view hierarchy.
When I have a RecyclerView, for get the current view position I do:
if(view.getParent() instanceof RecyclerView){
RecyclerView rv = (RecyclerView)view.getParent();
if(rv.getLayoutManager()!=null) {
position = rv.getLayoutManager().getPosition(view);
}
}
But when a ListView or GridView appears, I'm not able to get a Layout Manager to get the position of the view. The idea is to make it in a generic way, without knowing the Custom Adapter the view has.
I have tried to get the position through the ListView and GridView adapter but I dont see any method that do that.
Someone can help me?
Thank you a lot!
Create interface for get position for outside adapter class
here is adapter code:
public class ReportMediaAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<File> reportMediaList = new ArrayList<>();
private Context context;
private int selectedPos = -1;
private OnRemoveImage onRemoveImage;
public ReportMediaAdapter(Context context, ArrayList<File> reportMediaList, OnRemoveImage onRemoveImage) {
this.reportMediaList = reportMediaList;
this.onRemoveImage = onRemoveImage;
this.context = context;
}
**public interface OnRemoveImage {
void onRemove(int pos);
}**
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView iv_image, iv_remove;
public MyViewHolder(View itemView) {
super(itemView);
iv_image = itemView.findViewById(R.id.iv_image);
iv_remove = itemView.findViewById(R.id.iv_remove);
}
}
#Override
public int getItemCount() {
return reportMediaList.size()-1;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_media, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
try {
MyViewHolder menuItemHolder = (MyViewHolder) holder;
CommonMethods.loadImage(context, reportMediaList.get(position), menuItemHolder.iv_image);
menuItemHolder.iv_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**onRemoveImage.onRemove(position);**
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is activity code:
#Override
public void onRemove(int pos) {
// use adapter position
}
I have found a solution:
if(view.getParent() instanceof ViewGroup) {
position = ((ViewGroup)view.getParent()).indexOfChild(view);
}

How to set a progress for many progress-bars in RecyclerView

I am using a RecyclerView to view many Progress Bars as a slide show and an adapter.
This my adapter class
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.ViewHolder> {
private static final String TAG = "RecAdapter";
private ArrayList progressbars = new ArrayList<>();
private Context pcontex;
public RecAdapter(Context pcontex ,ArrayList progressbars) {
this.progressbars = progressbars;
this.pcontex = pcontex;
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.progress,viewGroup,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Log.d(TAG, "onBindViewHolder: called");
}
#Override
public int getItemCount() {
return progressbars.size() ;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ProgressBar b ;
ConstraintLayout parent;
public ViewHolder(#NonNull View itemView) {
super(itemView);
b = itemView.findViewById(R.id.progressBar);
parent= itemView.findViewById(R.id.parent);
}
}
}
My MainActivity code-
Prog = new ArrayList<>(); b2 = findViewById(R.id.progressBar) ;
b = findViewById(R.id.progressBar);
probitmap();
private void probitmap(){
Log.d(TAG, "probitmap: preparing bit maps");
Prog.add(b);
Prog.add(b2);
Recycle();// this method is out of on create
}
private void Recycle(){
Log.d(TAG, "Recycle: init recycleview");
recyclerView =findViewById(R.id.Rec);
RecAdapter Adapter = new RecAdapter(this,Prog);
recyclerView.setAdapter(Adapter);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
}
The code is working perfectly but I need to retrieve every progress bar that is in the recycle view and set progress for each one.
I tried multiple ways but it doesn't work. Here is what I tried-
for (int i = 0; i < recyclerView.getChildCount(); i++) {
RecAdapter.ViewHolder holder = (RecAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
holder.b.setProgress(50);
}
Use OnBindViewHolder to manage each "row" generated by the recycler.
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.b.setProgress(progressbar.get(i)); //i is the position of the recycler
viewHolder.b.setListener....
}

How to pass onClickHandler as parameter while setting adapter for a RecyclerView in a Fragment?

I made an Adapter for my recyclerView. This adapter works when I use on any xxxActivity.java but when I try to use is on a Fragment Its hows error. Doesn't let me Pass the onClickHandler() that I created in Adapter.
I am Setting Adapter Like this -
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, mClickHandler)); //ClickListener doesn't work :'(
Another try was like --
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, getmClickHandler()));
Here, I implemented getClickHandler() in the Fragment--
public FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler getmClickHandler() {
return mClickHandler;
} //Still doesn't work :'(
and the Adapter Part--
Constructor like this-
public FixedPlaceListAdapter(Context mContext, List<PlaceBean>
placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
I tried to do this ... but still doesn't work--
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler.mClickhandler));
here is my full adapter code-
public class FixedPlaceListAdapter extends RecyclerView.Adapter<FixedPlaceListAdapter.FixedPlaceListAdapterViewHolder> {
private final FixedPlaceListAdapterOnclickHandler mClickHandler;
Context mContext;
List<PlaceBean> placeBeanList;
public FixedPlaceListAdapter(Context mContext, List<PlaceBean> placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
public void setData(List<PlaceBean> placeBeanList) {
this.placeBeanList = placeBeanList;
notifyDataSetChanged();
}
#Override
public FixedPlaceListAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.top_list_single, parent, false);
return new FixedPlaceListAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(FixedPlaceListAdapterViewHolder holder, int position) {
PlaceBean pb = placeBeanList.get(position);
holder.nameTextView.setText(pb.getName());
holder.addressTextView.setText(pb.getVicinity());
holder.rating.setRating(pb.getRating());
if (pb.getPhotoref() != null) {
String imageUrl = UrlsUtil.getSinglePhotoUrlString(mContext, pb.getPhotoref(), "350", "300");
Picasso.with(mContext)
.load(imageUrl)
.into(holder.thumbnailImage);
}
}
#Override
public int getItemCount() {
return placeBeanList.size();
}
public interface FixedPlaceListAdapterOnclickHandler {
void onClick(String id);
}
public class FixedPlaceListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
RatingBar rating;
ImageView thumbnailImage;
public FixedPlaceListAdapterViewHolder(View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.place_name_now_in_list);
addressTextView = (TextView) itemView.findViewById(R.id.address_in_list);
rating = (RatingBar) itemView.findViewById(R.id.rating_single_place_in_list);
thumbnailImage = (ImageView) itemView.findViewById(R.id.place_image_thumb);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String placeID = placeBeanList.get(getAdapterPosition()).getPlaceref();
mClickHandler.onClick(placeID);
}
}
}
Need Help!
public class CategoryNewsListAdapter extends RecyclerView.Adapter<CategoryNewsListAdapter.ViewHolder> {
private List<CategoryNews> actors = new ArrayList<>();
private Context mContext;
private Queue<List<CategoryNews>> pendingUpdates =
new ArrayDeque<>();
**public interface NewsItemClickListener {
void onNewsItemClick(int pos, CategoryNews categoryNews, ImageView shareImageView);
}**
**NewsItemClickListener newsItemClickListener;**
public CategoryNewsListAdapter(List<CategoryNews> personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.particular_cat_news_list_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("BusinessSubCategoryListAdapter", "Bindviewholder without payload");
final CategoryNews newsCategory = actors.get(position);
holder.news_title.setText(newsCategory.getPostTitle());
holder.news_date.setText(newsCategory.getPostDate());
holder.news_category.setText(newsCategory.getCategoryName());
holder.news_description.setText(newsCategory.getPostContent());
// GlideApp
// .with(mContext).load(newsCategory.getPostImage())
// .placeholder(R.mipmap.ic_launcher) // can also be a drawable
// .error(R.drawable.placeholder_image) // will be displayed if the image cannot be loaded
// .crossFade()
// .into(holder.news_image);
Picasso.with(mContext).load(newsCategory.getPostImage()).placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image).into(holder.news_image);
**holder.itemView.setOnClickListener(v -> {
newsItemClickListener.onNewsItemClick(position, newsCategory, holder.news_image);
});**
}
#Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
// if empty, do full binding;
onBindViewHolder(holder, position);
return;
}
Bundle bundle = (Bundle) payloads.get(0);
String newTitle = bundle.getString("NAME_CHANGE");
if (newTitle != null) {
// add some animation if you want
final CategoryNews actor = actors.get(position);
holder.news_title.setText(actor.getPostTitle());
holder.news_date.setText(actor.getPostDate());
holder.news_category.setText(actor.getCategoryName());
holder.news_description.setText(actor.getPostContent());
}
}
public void addItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(curSize, newItems.size());
}
public void updtateItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(0,newItems.size()- getItemCount()-1);
}
#Override
public int getItemCount() {
return actors.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView news_title, news_date, news_category, news_description;
private ImageView news_image;
public ViewHolder(View itemView) {
super(itemView);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_category = (TextView) itemView.findViewById(R.id.news_category);
news_description = (TextView) itemView.findViewById(R.id.news_description);
news_image = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
And In your activity
implements NewsItemClickListener
create object NewsItemClickListener newsItemClickListner;
inside oncreate newsItemClickListner=this; (you mush have implemented 1)
pass that object to recyclerview.
In adapter it is received by this
public CategoryNewsListAdapter(List personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
In your activity
CategoryNewsListAdapter categoryNewsListAdapter= new CategoryNewsListAdapter(list,this,newsItemClickListner)
After doing all this your overriden method will be called when you click in item of recycler view where you have set onclick listner
Okay .. The Problem is Fixed now ...
I was passing the wrong value or maybe the method of passing the ClickHandler was wrong.
The Solution of the Problem :
I Created another Class for ClickHandler-
public class PlaceCardClickHandler implements
FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler,
PlaceListAdapter.PlaceListAdapterOnclickHandler {
Context mContext;
public PlaceCardClickHandler(Context mContext) {
this.mContext = mContext;
}
#Override
public void onClick(String id) {
Intent intentToStartDetail = new Intent(mContext, PlaceDetailActivity.class);
intentToStartDetail.putExtra("id", id);
mContext.startActivity(intentToStartDetail);
}
}
and the change in the Fragment was like this- (Just passed a object from the ClickHandler class)
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, new PlaceCardClickHandler(getContext())));

Calling activity from ViewHolder in RecyclerView?

I've got a RecyclerView which is loading the content of my String arrays which works fine, however I want to open a new activity depending on which view they have pressed.
What I have done is created an array called classes like so:
<array name="classes">
<item>ClassOne</item>
<item>ClassTwo</item>
<item>ClassThree</item>
<item>ClassFour</item>
</array>
These are stored in an array, and passed to my MainActivityList adapter below:
String[] classes = resource.getStringArray(R.array.classes);
MainActivityList adapter = new MainActivityList(titles,content, images, classes);
recyclerView.setAdapter(adapter);
I've managed to add the OnClickListener to the ViewHolder and output what class is assigned to each view to the log, however I cannot figure out or get working, how to launch another activity.
The class name would be something like ClassOne.class for example
public class MainActivityList extends RecyclerView.Adapter<MainActivityList.ViewHolder> {
private String[] mTitles;
private String[] mContent;
private String[] mClasses;
private TypedArray mImages;
private Context context;
public MainActivityList(String[] titles, String[] content, TypedArray images, String[] classes) {
this.mTitles = titles;
this.mContent = content;
this.mImages = images;
this.mClasses = classes;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup,int i) {
final View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_main_card, viewGroup, false);
ViewHolder vh = new ViewHolder(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder vh = (ViewHolder)v.getTag();
Log.v("DEBUG", "Clicked" + vh.classes);
}
});
return vh;
}
public void onBindViewHolder(ViewHolder holder, int position) {
holder.titleView.setText(mTitles[position]);
holder.contentView.setText(mContent[position]);
holder.imageView.setImageDrawable(mImages.getDrawable(position));
holder.classes = mClasses[position];
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView titleView;
public TextView contentView;
public ImageView imageView;
public String classes;
public ViewHolder(View v) {
super(v);
titleView = (TextView) v.findViewById(R.id.card_title);
contentView = (TextView) v.findViewById(R.id.card_content);
imageView = (ImageView)v.findViewById(R.id.card_image);
v.setTag(this);
}
}
#Override
public int getItemCount() {
return mTitles.length;
}
}
Intent intent = new Intent(viewObject.getContext(),ActivityName.class);
viewObject.getContext().startActivity(intent);
I was also looking for a solution, and I found this post:
http://venomvendor.blogspot.sg/2014/07/setting-onitemclicklistener-for-recycler-view.html
By using the OnItemClickListener interface, you should be able to call startActivity in your activity.
adapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View v , int position) {
// This is in an Activity so should be able to start new activity, etc.
}
});
Update: I have tested, the method mentioned in the blog worked for me.

Categories