I, have implemented view-pager in my project. Now I want when I click on particular view-pager It will open a new Detail Fragment. Where according to that Image Slider information is available.
Here is my code:
Adapter Code:
public class SliderImageAdapter extends SliderViewAdapter<SliderImageAdapter.SliderAdapterVH>{
public List<Banner> bannerList;
public Context context;
public SliderImageAdapter(Context context, List<Banner> bannerList) {
this.bannerList = bannerList;
this.context = context;
}
#Override
public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_myshop, parent, false);
return new SliderAdapterVH(inflate);
}
#Override
public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {
Glide.with(viewHolder.itemView)
.load(bannerList.get(position).getmSliderImage())
.fitCenter()
.into(viewHolder.imageViewBackground);
}
#Override
public int getCount() {
return bannerList.size();
}
public int getItemPosition (Object object) {
return POSITION_NONE;
}
class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
View itemView;
ImageView imageViewBackground;
ImageView imageGifContainer;
public SliderAdapterVH(View itemView) {
super(itemView);
imageViewBackground = itemView.findViewById(R.id.iv_auto_image_slider);
imageGifContainer = itemView.findViewById(R.id.iv_gif_container);
this.itemView = itemView;
}
}
}
Home Fragment Code:
private SliderImageAdapter sliderImageAdapter;
private List<Banner> bannerList;
sliderMyshop = view.findViewById(R.id.imageSlider);
sliderMyshop.setSliderAdapter(sliderImageAdapter);
sliderMyshop.setIndicatorAnimation(IndicatorAnimations.WORM); //set indicator animation by using SliderLayout.IndicatorAnimations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
sliderMyshop.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
sliderMyshop.setIndicatorSelectedColor(Color.WHITE);
sliderMyshop.setIndicatorUnselectedColor(Color.GRAY);
sliderMyshop.startAutoCycle();
mFirestore.collection("Banner").orderBy("mSliderImage", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot documentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
assert documentSnapshots != null;
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String doc_id = doc.getDocument().getId();
Banner banner = doc.getDocument().toObject(Banner.class).withDocId(doc_id);
bannerList.add(doc.getNewIndex(), banner);
sliderImageAdapter.notifyDataSetChanged();
} else if (doc.getType() == DocumentChange.Type.MODIFIED) {
String docID = doc.getDocument().getId();
Banner changedModel = doc.getDocument().toObject(Banner.class).withDocId(docID);
if (doc.getOldIndex() == doc.getNewIndex()) {
// Item changed but remained in same position
bannerList.set(doc.getOldIndex(), changedModel);
} else {
// Item changed and changed position
bannerList.remove(doc.getOldIndex());
bannerList.add(doc.getNewIndex(), changedModel);
}
} else if (doc.getType() == DocumentChange.Type.REMOVED) {
// remove
bannerList.remove(doc.getOldIndex());
}
sliderImageAdapter.notifyDataSetChanged();
}
}
});
Now I, want to open another fragment on click of a particular image. According to position. Please guide me how to do that.
You need to add Onclicklistener on imageview in onBindViewHolder method:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
Then you need to separate Activity and call that activity in onclick method just like this:
context.startActivity(new Intent(context,DetailActivity.class))
You can also add fragment to this DetailActivity.
Related
Problem
In my acitvity i have two recyclerViews showing popular movies and top rated movies respectively.
When I click on a movie in a recyclerView, that movie is sent to an activity showing its details.
I go back to the home and if I click on a movie of another recyclerView, the previously clicked movie is shown.
I need to show the details of any clicked movie in any recyclerView.
I have a single viewHolder (MovieViewHolder)
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//Widgets
TextView title, rating;
ImageView imageView;
//Click listener
OnMovieListener onMovieListener ;
public MovieViewHolder(#NonNull View itemView, OnMovieListener onMovieListener) {
super(itemView);
this.onMovieListener = onMovieListener;
title = itemView.findViewById(R.id.movie_title);
imageView = itemView.findViewById(R.id.movie_img);
rating = itemView.findViewById(R.id.rating_bar);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onMovieListener.onMovieClick(getAdapterPosition());
}
An interface
public interface OnMovieListener {
void onMovieClick(int position);
void onCategoryClick(String category);
}
This two Adapter:
This for popular movies
public class MovieRecyclerView extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MovieModel> mMovies;
private final OnMovieListener onMovieListener;
public MovieRecyclerView(OnMovieListener onMovieListener) {
this.onMovieListener = onMovieListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item,
parent, false);
return new MovieViewHolder(view, onMovieListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((MovieViewHolder) holder).title.setText(mMovies.get(position).getTitle());
((MovieViewHolder) holder).rating.setText(String.valueOf((float) (mMovies.get(position).getVote_average())));
//ImageView: Using Glide Library
Glide.with(holder.itemView.getContext())
.load("https://image.tmdb.org/t/p/w500/"
+ mMovies.get(position).getPoster_path())
.into(((MovieViewHolder) holder).imageView);
}
#Override
public int getItemCount() {
if (mMovies != null) {
return mMovies.size();
}
return 0;
}
public void setmMovies(List<MovieModel> mMovies) {
this.mMovies = mMovies;
notifyDataSetChanged();
}
//Getting the id of the movie clicked
public MovieModel getSelectedMovie(int position) {
if (mMovies != null) {
if (mMovies.size() > 0) {
return mMovies.get(position);
}
}
return null;
}
This for top_rated
public class MovieLatestRecyclerView extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MovieModel> mMoviesLatest;
private OnMovieListener onMovieListener;
public MovieLatestRecyclerView(OnMovieListener onMovieListener) {
this.onMovieListener = onMovieListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item,
parent, false);
return new MovieViewHolder(view, onMovieListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((MovieViewHolder)holder).title.setText(mMoviesLatest.get(position).getTitle());
((MovieViewHolder)holder).rating.setText(String.valueOf((float) (mMoviesLatest.get(position).getVote_average())));
//ImageView: Using Glide Library
Glide.with(holder.itemView.getContext())
.load("https://image.tmdb.org/t/p/w500/"
+ mMoviesLatest.get(position).getPoster_path())
.into(((MovieViewHolder)holder).imageView);
}
#Override
public int getItemCount() {
if(mMoviesLatest != null) {
return mMoviesLatest.size();
}
return 0;
}
public void setmMoviesLatest(List<MovieModel> mMoviesLatest) {
this.mMoviesLatest = mMoviesLatest;
notifyDataSetChanged();
}
//Getting the id of the movie clicked
public MovieModel getSelectedMovie(int position){
if(mMoviesLatest != null){
if(mMoviesLatest.size() > 0){
return mMoviesLatest.get(position);
}
}
return null;
}
In MainActivity i configure the recyclerViews with this method
private void ConfigureRecyclerView() {
movieRecyclerViewAdapter = new MovieRecyclerView(this);
movieLatestRecyclerViewAdapter = new MovieLatestRecyclerView(this);
recyclerView_popular.setAdapter(movieRecyclerViewAdapter);
recyclerView_popular.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView_latest.setAdapter(movieLatestRecyclerViewAdapter);
recyclerView_latest.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
//RecyclerView Pagination
//Loading next page of api response
recyclerView_popular.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
if (!recyclerView.canScrollVertically(1)) {
//Here we need to display the next search result
movieListViewModel.searchNextPage();
}
}
});
recyclerView_latest.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
if (!recyclerView.canScrollVertically(1)) {
//Here we need to display the next search result
movieListViewModel.searchNextPage();
}
}
});
}
And i use this for passing the selected movie to another activity
#Override
public void onMovieClick(int position) {
//WE don't need position of the movie in recyclerView
// We need the ID of the movie in order to get all it's details
Intent intent = new Intent(this, MovieDetails.class);
intent.putExtra("movie", movieRecyclerViewAdapter.getSelectedMovie(position));
startActivity(intent);
}
Whoever you are reading my question I thank you for your time and I apologize for the certain banality and length.
At this line:
intent.putExtra("movie", movieRecyclerViewAdapter.getSelectedMovie(position));
You are getting a movie from movieRecyclerViewAdapter. This adapter is only used with the 'Popular' movie recycler view.
onMovieClick is used for both the 'Popular' and the 'Top Rated' recycler views. So, clicking an item from 'Top Rated' will attempt to use an item from 'Popular'.
To fix this, a click from 'Top Rated' should not attempt to get an item from movieRecyclerViewAdapter.
You could do something like change onMovieClick(int position) to onMovieClick(MovieModel movie), so you don't have to worry about knowing which adapter to get the movie from.
I have a recyclerview whose listitem is designed as follows
LinearLayout(Horizontal)
ImageView
TextView
ImageButton(PlayButton)
EqualizerView(Invisible)
Now when I click on PlayButton, it should hide and equalizer show be displayed and if I scroll the list, equalizer should stay on selected item only.
However, I am facing problem that EqualizerView is being displayed at interval of 10 items. That is if I click on 3rd item then equalizer will be displayed on 3rd,13th and so on..
I am using this https://github.com/claucookie/mini-equalizer-library-android library for implementing mini equalizer.
public class StationViewAdapter extends RecyclerView.Adapter<StationViewAdapter.StationViewHolder> {
List<Station> statons;
final private ListItemClickListener mOnClickListener;
public StationViewAdapter (List<Station> s, ListItemClickListener l)
{
statons = s;
mOnClickListener = l;
}
#NonNull
#Override
public StationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new StationViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final StationViewHolder holder, int position) {
Station station = statons.get(position);
if(!station.getArtwork().isEmpty() && station.getArtwork() != null)
{
try{
Picasso.get().load(Uri.parse(station.getArtwork()))
// .placeholder(R.mipmap.ic_launcher)
.into(holder.stationArtwork);
} catch (Exception e) {
e.printStackTrace();
holder.stationArtwork.setImageResource(R.mipmap.ic_launcher);
}
}
else
holder.stationArtwork.setImageResource(R.mipmap.ic_launcher);
holder.stationName.setText(station.getName());
}
#Override
public int getItemCount() {
return statons.size();
}
public class StationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView stationArtwork;
TextView stationName;
ImageButton stationPlayButton;
EqualizerView equalizerView;
int selectedItem;
public StationViewHolder(#NonNull View itemView) {
super(itemView);
stationArtwork = itemView.findViewById(R.id.favicon);
stationName = itemView.findViewById(R.id.text);
stationPlayButton = itemView.findViewById(R.id.play_button);
equalizerView = itemView.findViewById(R.id.equalizer_view);
itemView.setOnClickListener(this);
stationPlayButton.setOnClickListener(this);
selectedItem = getAdapterPosition();
}
#Override
public void onClick(View v) {
int clickPosition = getAdapterPosition();
Log.d(TAG, "onClick: "+getAdapterPosition());
Log.d(TAG, "onClick: "+getLayoutPosition());
Log.d(TAG, "onClick: "+getItemId());
if(v == itemView) {
mOnClickListener.onListItemClick(clickPosition);
}else if(v == stationPlayButton)
{
mOnClickListener.onListItemPlay(clickPosition,stationPlayButton,equalizerView);
}
}
}
public interface ListItemClickListener {
void onListItemClick(int clickedItemIndex);
void onListItemPlay(int clickItemIndex,ImageButton i,EqualizerView eq);
}
}
These are ClickListeners in Main Activity
#Override
public void onListItemClick(int clickedItemIndex) {
if(mToast !=null)
{
mToast.cancel();
}
mToast = Toast.makeText(this,"Main Activity item clicked at position"+clickedItemIndex,Toast.LENGTH_SHORT);
mToast.show();
}
#Override
public void onListItemPlay(int clickItemIndex,ImageButton i , EqualizerView eq) {
i.setVisibility(View.GONE);
eq.setVisibility(View.VISIBLE);
eq.animateBars();
}
RecyclerView reuses ViewHolder instances. You need to invalidate ViewHolder state inside onBindViewHolder. In your case you should hide EqulizerView at least:
#Override
public void onBindViewHolder(#NonNull final StationViewHolder holder, int position) {
equalizerView.setVisibility(View.INVISIBLE);
....
}
Also, you should save which songs are playing to initialize ViewHolder state later.
More info at: https://developer.android.com/guide/topics/ui/layout/recyclerview#structure
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I, have implemented image slider using view-pager in my project. Now I want when I click on particular image of the slider. It will open a new Detail Fragment. Where according to that Image Slider information is available. So I tried to implement interface by getting image position using setOnClickListner. But now the problem is I am getting exception when I click on image. and my app gets crashed. Below is my code...
Slider Image Adapter:
public class SliderImageAdapter extends SliderViewAdapter<SliderImageAdapter.SliderAdapterVH>{
public List<Banner> bannerList;
public Context context;
private OnItemClicked onClick;
public interface OnItemClicked {
void onItemClick(int position);
}
public SliderImageAdapter(Context context, List<Banner> bannerList) {
this.bannerList = bannerList;
this.context = context;
}
#Override
public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_myshop, parent, false);
return new SliderAdapterVH(inflate);
}
#Override
public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {
Glide.with(viewHolder.itemView)
.load(bannerList.get(position).getmSliderImage())
.fitCenter()
.into(viewHolder.imageViewBackground);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClick(position);
}
});
}
#Override
public int getCount() {
return bannerList.size();
}
public int getItemPosition (Object object) {
return POSITION_NONE;
}
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick;
}
class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
View itemView;
ImageView imageViewBackground;
ImageView imageGifContainer;
public SliderAdapterVH(View itemView) {
super(itemView);
imageViewBackground = itemView.findViewById(R.id.iv_auto_image_slider);
imageGifContainer = itemView.findViewById(R.id.iv_gif_container);
this.itemView = itemView;
}
}
}
Here I am getting the exception in Image Slider Adapter: java.lang.NullPointerException: Attempt to invoke interface method SliderImageAdapter$OnItemClicked.onItemClick(int)' on a null object reference.
#Override
public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {
Glide.with(viewHolder.itemView)
.load(bannerList.get(position).getmSliderImage())
.fitCenter()
.into(viewHolder.imageViewBackground);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClick(position);
}
});
}
Home Fragment Code:
public class HomeFragment extends Fragment implements SliderImageAdapter.OnItemClicked {
private SliderImageAdapter sliderImageAdapter;
private List<Banner> bannerList;
bannerList = new ArrayList<>();
sliderImageAdapter = new SliderImageAdapter(getActivity(), bannerList);
sliderMyshop = view.findViewById(R.id.imageSlider);
sliderMyshop.setSliderAdapter(sliderImageAdapter);
sliderMyshop.setIndicatorAnimation(IndicatorAnimations.WORM); //set indicator animation by using SliderLayout.IndicatorAnimations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
sliderMyshop.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
sliderMyshop.setIndicatorSelectedColor(Color.WHITE);
sliderMyshop.setIndicatorUnselectedColor(Color.GRAY);
sliderMyshop.startAutoCycle();
mFirestore.collection("Banner").orderBy("mSliderImage", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot documentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
assert documentSnapshots != null;
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String doc_id = doc.getDocument().getId();
Banner banner = doc.getDocument().toObject(Banner.class).withDocId(doc_id);
bannerList.add(doc.getNewIndex(), banner);
sliderImageAdapter.notifyDataSetChanged();
} else if (doc.getType() == DocumentChange.Type.MODIFIED) {
String docID = doc.getDocument().getId();
Banner changedModel = doc.getDocument().toObject(Banner.class).withDocId(docID);
if (doc.getOldIndex() == doc.getNewIndex()) {
// Item changed but remained in same position
bannerList.set(doc.getOldIndex(), changedModel);
} else {
// Item changed and changed position
bannerList.remove(doc.getOldIndex());
bannerList.add(doc.getNewIndex(), changedModel);
}
} else if (doc.getType() == DocumentChange.Type.REMOVED) {
// remove
bannerList.remove(doc.getOldIndex());
}
sliderImageAdapter.notifyDataSetChanged();
}
}
});
#Override
public void onItemClick(int position) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container_dashboard, SliderClickFragment.newInstance(bannerList.get(position).getmSliderImage()));
ft.addToBackStack(null); // this line responsible for adding fragment in backstack.
ft.commit();
}
Detail Fragment Code:
public abstract class SliderClickFragment extends Fragment {
public static Fragment newInstance(String getmSliderImage) {
Bundle args = new Bundle();
HomeFragment fragment = new HomeFragment();
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.slider_click_listner, container, false);
return view;
}
}
So the issue would probably be that you are calling the OnItemClicked.onClick without an instance of OnItemClicked.
Just a quick look through
private OnItemClicked onClick;
public interface OnItemClicked {
void onItemClick(int position);
}
public SliderImageAdapter(Context context, List<Banner> bannerList) {
this.bannerList = bannerList;
this.context = context;
}
And then you use it here
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClick(position);
}
});
You are using trying to call the OnClick method on a null instance of OnItemClicked.
One way to do it would be to add OnItemClicked onclick to the contructor as a parameter and then have what ever fragment implement the OnItemClicked interface.
Something like this.
private OnItemClicked onClick;
public interface OnItemClicked {
void onItemClick(int position);
}
public SliderImageAdapter(Context context, List<Banner> bannerList,
OnItemClicked onClick) {
this.bannerList = bannerList;
this.onClick = onClick;
this.context = context;
}
Then at the HomeFragment
public class HomeFragment extends Fragment implements
SliderImageAdapter.OnItemClicked{
private SliderImageAdapter sliderImageAdapter
= new SliderImageAdapter(getActivity(), bannerList, this);
}
I'm creating an Android app, the data that i'm sending through intent is being retrieved every time i click on the item.
I'm sending the retrieved data(which it's a subcollection that is being retrieved every time i click on item) through the intent,and all data receives in an arraylist, so the listener don't know if the same data existed in the arraylist,because the data are in the other activity.
when i click for the first time the data displayed normally in ItemMarkerActivity but when i go back and click again on the same item i see the data load again in the recycler view,and added to the previous same data, i'm using the technique of removing the data onStop but it didn't work perfectly,because i need to close all activities to see that the data removed, i tried to send the CollectionReference through intent but i couldn't do. so I need a way of removing the data immediately after closing the activity, and if anyone has another approach for solving this problem it would better.
Thanks in advance
adapter.setOnItemClickListener(new MarketAdapterRecyclerView.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
CollectionReference path = documentSnapshot.getReference().collection("ShoppingItems");
listener = path.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
if (dc.getType() == DocumentChange.Type.ADDED) {
item = dc.getDocument().toObject(Item.class);
itemList.add(item);
}
}
Intent intent = new Intent (shoppingActivity.this, ItemMarkerActivity.class);
Log.v(TAG,"###################################" + itemList.toString());
intent.putExtra("keyName", itemList);
startActivity(intent);
}
});
}
}
The Activity That Receives The data
The Manifest
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> implements Parcelable{
public ArrayList<Item> ItemList;
public Context mContext;
private onMallListener mOnMallListener;
private static final int NO_POSITION = -1;
public ItemAdapter(ArrayList<Item> ItemList, Context mContext, onMallListener mOnMallListener) {
this.ItemList = ItemList;
this.mContext = mContext;
this.mOnMallListener = mOnMallListener;
}
protected ItemAdapter(Parcel in) {
ItemList = in.createTypedArrayList(Item.CREATOR);
}
public static final Creator<ItemAdapter> CREATOR = new Creator<ItemAdapter>() {
#Override
public ItemAdapter createFromParcel(Parcel in) {
return new ItemAdapter(in);
}
#Override
public ItemAdapter[] newArray(int size) {
return new ItemAdapter[size];
}
};
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_card_view_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view, mOnMallListener);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Item item = ItemList.get(i);
viewHolder.itemType.setText(ItemList.get(i).getItemType());
Picasso.with(mContext)
.load(item.getImageUrl())
.fit()
.centerCrop().into(viewHolder.imageUrl);
}
#Override
public int getItemCount() {
return ItemList.size();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(ItemList);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
public TextView price;
public TextView description;
public TextView itemType;
public ImageView imageUrl;
onMallListener onMallListener;
public ViewHolder(#NonNull View itemView, onMallListener mOnMallListener) {
super(itemView);
mView = itemView;
itemType = (TextView) mView.findViewById(R.id.card_view_image_title);
imageUrl = (ImageView) mView.findViewById(R.id.card_view_image);
this.onMallListener = mOnMallListener;
mView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(mOnMallListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mOnMallListener.onMallClick(position);
}
}
}
}
public interface onMallListener{
void onMallClick(int position);
}
}
Save data using Room database in first activity and retrieve it in second.
In any place of your code (and in any activity's callback) you can clean db and all lists/recyclers which listen this data.
https://developer.android.com/training/data-storage/room
Hope it'll help
I want to highlight the selected items in recyclerview. I can count the number of items selected.
I want the highlighting as
.....
I have tried this code.
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (isMultiSelect) {
multi_select(position);
selectedPositon = position;
} else{
Toast.makeText(getApplicationContext(), "Details Page", Toast.LENGTH_SHORT).show();
}
if (selectedPositon == position) {
view.setBackgroundColor(Color.parseColor("#e2a49e"));
} else {
view.setBackgroundColor(Color.parseColor("#f5f5f5"));
}
}
#Override
public void onItemLongClick(View view, int position) {
if (!isMultiSelect) {
selected_list = new ArrayList<AlertListItem>();
isMultiSelect = true;
selectedPositon = position;
if (mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
if (selectedPositon == position) {
view.setBackgroundColor(Color.parseColor("#e2a49e"));
} else {
view.setBackgroundColor(Color.parseColor("#f5f5f5"));
}
multi_select(position);
}
}));
}
can someone help me out.
if (btn.getBackground().getConstantState().equals(itemView.getResources().getDrawable(R.drawable.understand_clicked).getConstantState())) {
btn.setBackground(itemView.getResources().getDrawable(R.drawable.understand_not_clicked));
} else {
btn.setBackground(itemView.getResources().getDrawable(R.drawable.understand_clicked));
}
Do this code in a custom recyclerviewadapter, in View holder class. Use getConstantState for current state of image. You can also change color of selected raw.
you can use use below code
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.textView.setText(array[position]);
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
index=position;
notifyDataSetChanged();
}
});
if(index==position){
holder.layout.setBackgroundColor(Color.parseColor("#ff8569"));
holder.textView.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.layout.setBackgroundColor(Color.parseColor("#ffffff"));
holder.textView.setTextColor(Color.parseColor("#000000"));
}
}
HolderClass
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
LinearLayout layout;
RecyclerView recyclerView;
public ViewHolder(final View itemView) {
super(itemView);
textView=(TextView)itemView.findViewById(R.id.textView1);
layout=(LinearLayout)itemView.findViewById(R.id.layouot_linear);
recyclerView=(RecyclerView)itemView.findViewById(R.id.recycler);
}
}