Hide the visibility of the nested recyclerview in android on ChildItem Click - android

I have a nested recycler view on which child item click I want the whole child recycler view to set visibility GONE.
I have tried some way to do it. But keeps on loosing the recycler view state and wrong data show's up. Help, please.
Here is ParentAdapter.java code
public class MessageListAdapter extends RecyclerView.Adapter {
private Context mContext;
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
private List<Payload> chatMessageList;
private RecyclerView.RecycledViewPool recycledViewPool;
private OnItemClickListener onItemClickListener;
MessageListAdapter(Context context, List<Payload> chatMessageList, OnItemClickListener onItemClickListener) {
this.mContext = context;
this.chatMessageList = chatMessageList;
this.onItemClickListener = onItemClickListener;
recycledViewPool = new RecyclerView.RecycledViewPool();
}
#Override
public int getItemCount() {
return chatMessageList.size();
}
// Determines the appropriate ViewType according to the sender of the message.
#Override
public int getItemViewType(int position) {
Payload message = chatMessageList.get(position);
if (TextUtils.equals(message.getUserType(), "USER")) {
// If the current user is the sender of the message
return VIEW_TYPE_MESSAGE_SENT;
} else {
// If some other user sent the message
return VIEW_TYPE_MESSAGE_RECEIVED;
}
}
// Inflates the appropriate layout according to the ViewType.
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == VIEW_TYPE_MESSAGE_SENT) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_msg, parent, false);
return new SentMessageHolder(view);
} else {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_bot_msg, parent, false);
return new ReceivedMessageHolder(view);
}
}
// Passes the message object to a ViewHolder so that the contents can be bound to UI.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Payload chatMessage = chatMessageList.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_SENT:
((SentMessageHolder) holder).bind(chatMessage.getMessage(), getFormattedTime());
break;
case VIEW_TYPE_MESSAGE_RECEIVED:
((ReceivedMessageHolder) holder).bind(chatMessage.getMessage(), getFormattedTime());
((ReceivedMessageHolder) holder).bindRv(chatMessage, mContext, recycledViewPool, onItemClickListener);
break;
}
}
private static class SentMessageHolder extends RecyclerView.ViewHolder {
TextView txtViewChatMsgUser;
TextView txtViewDateTimeUser;
SentMessageHolder(View itemView) {
super(itemView);
txtViewChatMsgUser = itemView.findViewById(R.id.txtViewChatMsgUser);
txtViewDateTimeUser = itemView.findViewById(R.id.txtViewDateTimeUser);
}
void bind(String message, String time) {
txtViewChatMsgUser.setText(message);
txtViewDateTimeUser.setText(time);
}
}
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
TextView txtViewChatMsgBot;
RecyclerView rvDeepLink;
TextView txtViewDateTimeBot;
ReceivedMessageHolder(View itemView) {
super(itemView);
txtViewChatMsgBot = itemView.findViewById(R.id.txtViewChatMsgBot);
rvDeepLink = itemView.findViewById(R.id.itemRvDeepLink);
txtViewDateTimeBot = itemView.findViewById(R.id.txtViewDateTimeBot);
}
void bind(String message, String time) {
txtViewChatMsgBot.setText(message);
txtViewDateTimeBot.setText(time);
}
void bindRv(Payload chatMessage, Context context, RecyclerView.RecycledViewPool recycledViewPool, OnItemClickListener onItemClickListener) {
if (chatMessage.getData() != null && !chatMessage.isOptionSelected()) {
DeepLinkAdapter deepLinkAdapter = new DeepLinkAdapter(context, chatMessage.getData(), onItemClickListener, getAdapterPosition());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
rvDeepLink.setLayoutManager(linearLayoutManager);
rvDeepLink.setAdapter(deepLinkAdapter);
rvDeepLink.setRecycledViewPool(recycledViewPool);
deepLinkAdapter.notifyDataSetChanged();
} else {
rvDeepLink.setVisibility(View.GONE);
}
}
}
private String getFormattedTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa", Locale.ENGLISH);
return dateFormat.format(new Date());
}
public void clearData() {
chatMessageList.clear();
notifyDataSetChanged();
}
public void onSelected(int position) {
chatMessageList.get(position).setOptionSelected(true);
notifyItemChanged(position);
}
}
Here is my ChildAdapter.java code:
public class DeepLinkAdapter extends RecyclerView.Adapter<DeepLinkAdapter.DeepLinkViewHolder> {
private List<DataItem> dataItemList;
private Context context;
private OnItemClickListener onItemClickListener;
private int parentPos;
DeepLinkAdapter(Context context, List<DataItem> dataItemList, OnItemClickListener onItemClickListener, int parentPos) {
this.context = context;
this.dataItemList = dataItemList;
this.onItemClickListener = onItemClickListener;
this.parentPos = parentPos;
}
#NonNull
#Override
public DeepLinkViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DeepLinkViewHolder(LayoutInflater.from(context).inflate(R.layout.inner_bot_msg, parent, false), onItemClickListener, parentPos);
}
#Override
public void onBindViewHolder(#NonNull final DeepLinkViewHolder holder, final int position) {
DataItem dataItem = dataItemList.get(position);
if (TextUtils.isEmpty(dataItem.getDeeplink())) {
holder.deepLinkText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
holder.deepLinkText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_right_arrow, 0);
}
if (!TextUtils.isEmpty(dataItem.getText())) {
holder.deepLinkText.setVisibility(View.VISIBLE);
holder.deepLinkText.setText(dataItem.getText());
} else {
holder.deepLinkText.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
if (dataItemList != null) {
return dataItemList.size();
} else {
return 0;
}
}
class DeepLinkViewHolder extends RecyclerView.ViewHolder {
private TextView deepLinkText;
DeepLinkViewHolder(View itemView, OnItemClickListener onItemClickListener, int parentPos) {
super(itemView);
deepLinkText = itemView.findViewById(R.id.innerDeepLinkMsgText);
if (onItemClickListener != null) {
deepLinkText.setOnClickListener(v -> {
onItemClickListener.onItemClick(getAdapterPosition(), parentPos);
});
}
}
}
}
Here is my Click Listener Code in the Activity:
#Override
public void onItemClick(int childPos, int parentPos) {
if (TextUtils.isEmpty(chatMessageList.get(parentPos).getData().get(childPos).getDeeplink())) {
String message = chatMessageList.get(parentPos).getData().get(childPos).getText();
if (!viewModel.sendMessage(message)) {
setMessage(getString(R.string.error_something_went_wrong), ChatBotManager.UserType.BOT.toString());
} else {
messageListAdapter.onSelected(parentPos);
setMessage(message, ChatBotManager.UserType.USER.toString());
}
} else {
if (TextUtils.equals(chatMessageList.get(parentPos).getData().get(childPos).getDeeplink(), "restart")) {
if (messageListAdapter != null) {
messageListAdapter.clearData();
viewModel.sendMessage("start");
}
} else {
String uri = chatMessageList.get(parentPos).getData().get(childPos).getDeeplink();
Intent newIntent = new Intent(ApplicationClass.getContext(), TalkLinkingActivity.class);
newIntent.setData(Uri.parse(uri));
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
finish();
}
}
}
Please help what I am missing here, My goal is to have a click listener from the child adapter on Activity, and also after the click on the item, I want to remove the whole recycler view. Just like a chatbot in Swiggy.

Have a method in DeepLinkAdapter that clears the whole list:
public class DeepLinkAdapter extends RecyclerView.Adapter<DeepLinkAdapter.DeepLinkViewHolder> {
.......
public void clearTheWholeList(){
dataItemList.clear();
notifyDataSetChanged();
}
}
Have a method in your MessageListAdapter that removes an item completely:
public class MessageListAdapter extends RecyclerView.Adapter {
......
......
private int positionToClear = -1;
public void removeItem(int position){
positionToClear = position;
notifyDataSetChanged();
}
//in onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
............
............
//pass the positionToClear here
((ReceivedMessageHolder) holder).bindRv(chatMessage, mContext, recycledViewPool, onItemClickListener , positionToClear);
}
.......
}
In ReceivedMessageHolder
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
//here add new param for removed position
void bindRv(Payload chatMessage, Context context, RecyclerView.RecycledViewPool recycledViewPool, OnItemClickListener onItemClickListener, int positionToClear) {
if (chatMessage.getData() != null && !chatMessage.isOptionSelected()) {
DeepLinkAdapter deepLinkAdapter = new DeepLinkAdapter(context, chatMessage.getData(), onItemClickListener, getAdapterPosition());
//do a check here
if(getAdapterPosition() == positionToClear){
deepLinkAdapter.clearTheWholeList();
}
.......
.......
.......
} else {
rvDeepLink.setVisibility(View.GONE);
}
}
}
Assuming the onItemClick interface is working:
#Override
public void onItemClick(int childPos, int parentPos) {
...........
...........
//somewhere where you want the item to be removed
messageListAdapter.removeItem(parentPos);
............
............
}

Related

Android Recycler View Adapter OnClickListener inside another Adapter

I have the following Adapter :
public class TeambuilderAdapter extends RecyclerView.Adapter<TeambuilderAdapter.ViewHolder> implements ItemTouchHelperAdapter {
private List<PokemonTeam> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
private Context mContext;
private PokemonFavoritesAdapter pokemonFavoritesAdapter;
private GridLayoutManager gridLayoutManager;
// data is passed into the constructor
public TeambuilderAdapter(Context context, List<PokemonTeam> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
mContext = context;
setHasStableIds(true);
}
#Override
public long getItemId(int position) {
PokemonTeam pokemonTeam = mData.get(position);
return (pokemonTeam.getName()).hashCode();
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_item_teambuilder, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
PokemonTeam pokemonTeam = mData.get(position);
gridLayoutManager = new GridLayoutManager(mContext, 6);
pokemonFavoritesAdapter = new PokemonFavoritesAdapter(mContext, pokemonTeam.getPokemonList());
holder.teamSpritesRecyclerView.setAdapter(pokemonFavoritesAdapter);
holder.teamSpritesRecyclerView.setLayoutManager(gridLayoutManager);
String pokemonTeamName = pokemonTeam.getName();
if (pokemonTeamName != null && !pokemonTeamName.isEmpty()) {
holder.teamTitleTextView.setText(pokemonTeam.getName());
}
}
// total number of rows
#Override
public int getItemCount() {
int size = 0;
if (Objects.nonNull(mData)) {
size = mData.size();
}
return size;
}
#Override
public void onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mData, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mData, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
((PokemonTeambuilderActivity) mContext).refreshTeamList();
}
#Override
public void onItemDismiss(int position) {
mData.remove(position);
notifyItemRemoved(position);
((PokemonTeambuilderActivity) mContext).refreshTeamList();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView teamTitleTextView;
RecyclerView teamSpritesRecyclerView;
CardView pokemonTeambuilderContainer;
ViewHolder(View itemView) {
super(itemView);
teamTitleTextView = itemView.findViewById(R.id.pokemonTeambuilderTitleTextView);
teamSpritesRecyclerView = itemView.findViewById(R.id.pokemonTeambuilderSpritesLayout);
pokemonTeambuilderContainer = itemView.findViewById(R.id.pokemonTeambuilderContainer);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
// convenience method for getting data at click position
public PokemonTeam getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
In onBindViewHolder method I call another adapter inside this adapter which follows the same OnClickListener structure :
public class PokemonFavoritesAdapter extends RecyclerView.Adapter<PokemonFavoritesAdapter.ViewHolder> {
private Context mContext;
private List<Pokemon> favoritePokemon;
private LayoutInflater mInflater;
private PokemonFavoritesAdapter.ItemClickListener mClickListener;
public PokemonFavoritesAdapter(Context context, List<Pokemon> list) {
this.mInflater = LayoutInflater.from(context);
mContext = context;
favoritePokemon = list;
}
#NonNull
#Override
public PokemonFavoritesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_item_pokemon_favorite, parent, false);
return new PokemonFavoritesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokemonFavoritesAdapter.ViewHolder holder, int position) {
Pokemon pokemon = favoritePokemon.get(position);
String pokemonId = pokemon.get_id();
int dominantColor = PokemonUtils.getDominantColorFromPokemon(pokemonId, mContext);
int lighterDominantColor = PokemonUtils.lighterColor(dominantColor, GenericConstants.DARK_FACTOR);
int pokemonImageId = PokemonUtils.getPokemonSugimoriImageById(pokemonId, mContext);
holder.circularImageView.setBorderColor(dominantColor);
holder.circularImageView.setBorderWidth(4);
holder.circularImageView.setCircleColor(lighterDominantColor);
holder.circularImageView.setShadowRadius(6);
Picasso.get().load(pokemonImageId).fit().into(holder.circularImageView);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
int size = 0;
if (Objects.nonNull(favoritePokemon) && !favoritePokemon.isEmpty()) {
size = favoritePokemon.size();
}
return size;
}
// convenience method for getting data at click position
public Pokemon getItem(int id) {
return favoritePokemon.get(id);
}
// allows clicks events to be caught
public void setClickListener(PokemonFavoritesAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircularImageView circularImageView;
ViewHolder(View view) {
super(view);
circularImageView = view.findViewById(R.id.civ_pokemon_favorite);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
}
However I have a problem , my activity can't listen the click events that happens inside my nested adapter :
public class PokemonTeambuilderActivity extends AppCompatActivity implements TeambuilderAdapter.ItemClickListener {
#Override
public void onItemClick(View view, int position) {
}
I don't know how to reach the events that happens within my PokemonFavoritesAdapter in my TeambuilderAdapter , I supose that I must implement the PokemonFavoritesAdapter.OnClickListener interface in my TeambuilderAdapter but I don't know how to do it . Any hint ?

How to pass ArrayList from Adapter to activity?

I need send ArrayList list_add to activity but I don't know how I can do it if is possible share it on main activity for use it in the future.
Anyone can help me to implement a method for do it?
below have MainAdatper for recyclerview where I have a list_add and want passed it to main activity and after I can add it to
class MainAdapter extends RecyclerView.Adapter <MainAdapter.ViewHolder> {
private static int lastCheckedPos = 0;
ArrayList<String> list_add = new ArrayList<>();
ArrayList<String> lista_show;
private Context context;
String t;
public MainAdapter(ArrayList<String> lista_shows, Context context) {
lista_show = lista_shows;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final MainAdapter.ViewHolder holder, final int position) {
holder.mdevice.setText (lista_show.get (position));
holder.cardView.setOnLongClickListener (new View.OnLongClickListener () {
#Override
public boolean onLongClick(View v) {
t = lista_show.get(position);
if (list_add.contains(t)) {
Toast.makeText(v.getContext (), t+"Already Selected", Toast.LENGTH_SHORT).show();
} else {
list_add.add(t);
holder.cardView.setCardBackgroundColor(Color.parseColor("#60B5EC"));
Toast.makeText(v.getContext (), t+"Added", Toast.LENGTH_SHORT).show();
}
return true;
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t = lista_show.get (position);
holder.cardView.setCardBackgroundColor(Color.WHITE);
if (! list_add.contains(t)) {
Toast.makeText(v.getContext (), "Long press for add", Toast.LENGTH_SHORT).show();
} else {
list_add.remove(t);
Toast.makeText(v.getContext (), t+"Removed", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return lista_show.size ();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mdevice;
CardView cardView;
public ViewHolder( View itemView) {
super (itemView);
mdevice = itemView.findViewById (R.id.device);
cardView = itemView.findViewById (R.id.mcardview);
}
}
}
Add interface for callback:
public interface ListOwner {
void push(ArrayList<String> list);
}
Set refernce in adapter:
private ListOwner listOwner;
public MainAdapter(ArrayList<String> lista_shows, Context context, ListOwner owner) {
this.lista_show = lista_shows;
this.listOwner = owner;
}
The call it in adapter when you need:
if (listOwner != null) {
listOwner.push(list_add);
}
Of course, implement ListOwner by your activity:
public class MyActivity extends AppCompatActivity implements ListOwner {
// all code
// create instance of adapter:
mAdapter = new MainAdapter(list_show, MyActivity.this, MyActivity.this);
#Override
public void push(ArrayList<String> list) {
// you have the list here
}
}
P.S.
You can omit interface and pass reference to the Activity directly (MyActivity in the sample)

Animation on notifyDataSetChanged() in FragmentStatePagerAdapter

By overwriting getItemPosition() method I can refresh my FragmentStatePagerAdapter, which works fine. But the change of the contents is not nice to see.
Is there possibility to apply any kind of animation as I refresh the FragmentStatePagerAdapter?
I was also facing same issue.So, what should you do. Make global variables in your adapter for what you want continuous animate.
Now when you start animation on button click. Pass value to global variables.
When you notifydatasetchanged it doesn't effect your animation.
I haven't found any correct way. So, did this thing.It's working perfect.
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private ArrayList<Response.DataBean> feedArrayList = new ArrayList<>();
FeedClickListener mListener;
#Inject
ImageUtility mImageUtility;
#Inject
AppUtils mAppUtils;
#Inject
PreferenceManager mPref;
private float prevPosition = -1;
private YoYo.YoYoString ropeText,ropeImage;
private int tempHandlePlayPause = 0;
private TextView tempTextView;
private ImageView tempImageView;
/**
* click listeners
*/
interface FeedClickListener {
void onPlayAudioClicked( FeedResponse.DataBean feedItem, SeekBar audioProgress, int position);
void onPauseAudioClicked(FeedResponse.DataBean feedItem);
}
public HomeAdapter(Context context, ArrayList<Response.DataBean> mDataArrayList, HomeClickListener mFeedListener) {
((BaseApplication) context.getApplicationContext()).getAppComponent().inject(this);
this.mContext = context;
this.feedArrayList = mDataArrayList;
mListener = mFeedListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
ItemViewHolder holderItem = (ItemViewHolder) holder;
int adapterPosition = holder.getAdapterPosition() - 1;
holderItem.normalContainer.setVisibility(View.VISIBLE);
holderItem.bannerContainer.setVisibility(View.GONE);
setUpNormalItem(adapterPosition, holderItem);
}
}
private void setUpNormalItem(int adapterPosition, ItemViewHolder holder) {
FeedResponse.DataBean feedItem = feedArrayList.get(adapterPosition);
// set up data to current view holder items
setUpItems(holder, feedItem, adapterPosition);
}
private void setUpItems(ItemViewHolder holder, FeedResponse.DataBean feedItem, int position) {
if (feedItem.isstop()) {
holder.playImageView.setVisibility(View.GONE);
holder.pauseImageView.setVisibility(View.VISIBLE);
} else {
holder.playImageView.setVisibility(View.VISIBLE);
holder.pauseImageView.setVisibility(View.GONE);
holder.audioProgress.setProgress(0);
}
holder.playImageView.setOnClickListener(v -> {
feedItem.setIscomplete(false);
if (prevPosition >= 0) {
feedArrayList.get((int)prevPosition).setIsstop(false);
feedArrayList.get((int)prevPosition).setIsPrepare(false);
}
feedArrayList.get(position).setIsstop(true);
feedArrayList.get(position).setIsPrepare(true);
mListener.onPlayAudioClicked(feedItem, holder.audioProgress, position);
prevPosition = position;
tempHandlePlayPause = 1;
tempTextView = holder.tvPlayingBlink;
tempImageView = holder.pauseImageView;
notifyDataSetChanged();
});
holder.pauseImageView.setOnClickListener(v -> {
feedArrayList.get(position).setIsstop(false);
tempTextView = holder.tvPlayingBlink;
tempImageView = holder.pauseImageView;
tempHandlePlayPause = 0;
mListener.onPauseAudioClicked(feedItem);
notifyDataSetChanged();
});
if (feedItem.isPrepare()) {
holder.tvPlayingBlink.setVisibility(View.VISIBLE);
if (tempHandlePlayPause == 1){
startAnimation();
}else {
stopAnimation();
}
} else {
holder.tvPlayingBlink.setVisibility(View.INVISIBLE);
if (tempHandlePlayPause == 1){
startAnimation();
}else {
stopAnimation();
}
}
// play on complete audio
if (feedItem.iscomplete()) {
holder.playImageView.setVisibility(View.VISIBLE);
holder.pauseImageView.setVisibility(View.GONE);
}
if ((!feedItem.iscomplete()) && feedItem.getTotalLength() > 0) {
holder.audioProgress.setMax(feedItem.getTotalLength());
holder.audioProgress.setProgress(0);
}
}
private void startAnimation(){
if (ropeText != null || ropeImage != null) {
ropeText.stop(true);
ropeImage.stop(true);
}
ropeText = YoYo.with(Techniques.Pulse)
.duration(800)
.repeat(YoYo.INFINITE)
.pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
.interpolate(new AccelerateDecelerateInterpolator())
.playOn(tempTextView);
ropeImage = YoYo.with(Techniques.Pulse)
.duration(800)
.repeat(YoYo.INFINITE)
.pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
.interpolate(new AccelerateDecelerateInterpolator())
.playOn(tempImageView);
}
private void stopAnimation(){
if (ropeText != null || ropeImage != null) {
ropeText.stop(true);
ropeImage.stop(true);
}
}
public void updateData(List<FeedResponse.DataBean> items) {
feedArrayList.clear();
feedArrayList.addAll(items);
notifyDataSetChanged();
}
public void deleteItem(int position) {
feedArrayList.remove(position);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return (feedArrayList.size());
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.image_view_3)
ImageView imageView3;
#BindView(R.id.tvplayingblink)
TextView tvPlayingBlink;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}

RecyclerView in RecyclerView parent.notifyDataSetChanged loose position of child RecyclerView

I develop a fragment using Horizontal RecyclerView in a Vertical RecyclerView (like Google Play Store).
When i notifyDataSetChanged from the parent RecyclerView, the child RecyclerView lose the position because the setAdapter is call in the onBindViewHolder I think. Also when i scroll to the 5th position in the first horizontal recyclerview if i scroll down and come back up i loose the 5th position.
I try to use RecyclerView.scrollToPosition() but that don't work.
So i think i have two solution :
a way (by a method or setting) to keep the position of my child recycler view. (BEST SOLUTION)
a way to set manually the recyclerview position to where it was before the refresh. (ELSE SOLUTION)
Here my Parent Adapter :
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private ArrayList<AidodysProfile> sectionsList;
private Context context;
private boolean[] isShown;
private ProfileCardViewItemAdapter itemAdapters[];
public ProfilesCardViewListAdapter(ArrayList<AidodysProfile> sectionsList, Context context) {
this.sectionsList = sectionsList;
this.context = context;
this.isShown = new boolean[sectionsList.size()];
this.itemAdapters = new ProfileCardViewItemAdapter[sectionsList.size()];
for (int i = 0; i < sectionsList.size(); i++) {
this.isShown[i] = true;
this.itemAdapters[i] = new ProfileCardViewItemAdapter(sectionsList.get(i).getProfiles(), context, this);
}
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_card_view_horizontal, null);
final ItemRowHolder rowHolder = new ItemRowHolder(view);
return rowHolder;
}
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
String sectionName = sectionsList.get(position).getName();
AidodysProfile[] sectionItems = sectionsList.get(position).getProfiles();
holder.sectionTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_section_title));
holder.sectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showHideSection(holder, position);
}
});
if (isShown[position]) {
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
} else {
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
}
if (!sectionsList.get(position).isLeaf()) { // FOLDER
if (sectionName.equals("")) {
holder.sectionTitle.setVisibility(View.GONE);
holder.sectionButton.setVisibility(View.GONE);
} else {
holder.sectionTitle.setVisibility(View.VISIBLE);
holder.sectionButton.setVisibility(View.VISIBLE);
}
holder.sectionTitle.setText(sectionName);
} else { // PROFILE
return;
}
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
holder.itemRecyclerView.setAdapter(itemAdapters[position]);
}
private void showHideSection(ItemRowHolder holder, int position) {
if (holder.itemRecyclerView.getVisibility() == View.VISIBLE) {
isShown[position] = false;
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
} else {
isShown[position] = true;
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
}
}
#Override
public int getItemCount() {
return (sectionsList != null ? sectionsList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView sectionTitle;
protected RecyclerView itemRecyclerView;
protected Button sectionButton;
public ItemRowHolder(View view) {
super(view);
this.sectionTitle = (TextView) view.findViewById(R.id.section_title);
this.itemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view);
this.sectionButton = (Button) view.findViewById(R.id.section_button);
}
}
}
Child Adapter :
class ProfileCardViewItemAdapter extends RecyclerView.Adapter<ProfileCardViewItemAdapter.SingleItemRowHolder> {
private AidodysProfile[] itemsList;
private CurrentUser currentUser;
private Context context;
private int selectedPos = -1;
private ProfilesCardViewListAdapter parent;
public ProfileCardViewItemAdapter(AidodysProfile[] itemsList, Context context, ProfilesCardViewListAdapter parent) {
this.itemsList = itemsList;
this.context = context;
this.parent = parent;
this.currentUser = CurrentUser.getInstance(context);
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_view_horizontal, null);
SingleItemRowHolder rowHolder = new SingleItemRowHolder(view);
return (rowHolder);
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
AidodysProfile profile = itemsList[position];
holder.itemCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectProfile(holder, position);
}
});
if (profile.equals(currentUser.getProfile())) {
selectedPos = position;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.white));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.white));
}
}
holder.itemTitle.setText(profile.getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemPicture.setImageDrawable(context.getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.button1.setImageDrawable(context.getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getDrawable(R.drawable.ic_look_profile));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemTitle.setTextAppearance(R.style.Aidodys_Text_ProfilesList_Item);
holder.itemPicture.setColorFilter(context.getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
holder.button1.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_look_profile));
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
}
private void selectProfile(SingleItemRowHolder holder, int position) {
SharedPreferences.Editor editor = context.getSharedPreferences("Aidodys", 0).edit();
editor.putString("profile", new Gson().toJson(itemsList[position]));
editor.apply();
currentUser.setProfile(itemsList[position]);
parent.notifyDataSetChanged();
notifyDataSetChanged();
((RecyclerView)holder.itemCardView.getParent()).scrollToPosition(position);
selectedPos = position;
}
#Override
public int getItemCount() {
return (itemsList != null ? itemsList.length : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected ImageView itemPicture;
protected CardView itemCardView;
protected ImageView button1;
protected ImageView button2;
protected LinearLayout topParts;
public SingleItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView)view.findViewById(R.id.item_title);
this.itemPicture = (ImageView)view.findViewById(R.id.item_picture);
this.itemCardView = (CardView)view.findViewById(R.id.card_view_list_item);
this.topParts = (LinearLayout)view.findViewById(R.id.card_view_list_item_top_part);
this.button1 = (ImageView)view.findViewById(R.id.item_button_1);
this.button2 = (ImageView)view.findViewById(R.id.item_button_2);
}
}
}
If someone has a solution for me
Thank you
Store x scroll offset in a SparseArray for position and restore when bind view holder.
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private SparseIntArray sparseArray = new SparseIntArray();
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
// Use srollBy for animate scrolling
holder.itemRecyclerView.srollBy(sparseArray.get(position, 0), 0);
// Or scrollTo for restore previous x offset
//holder.itemRecyclerView.srollTo(sparseArray.get(position, 0), 0);
holder.itemRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
sparseArray.put(position, dx);
}
}
}
}
I found a solution, i use the onTouchListener in the child recyclerView to set a scrollPosition (i don't use onScrollListener because this method is deprecated) i implement a getter to this field to get the scroll position from the parent RecyclerView and so at the end of the onBindViewHolder in the parent RecyclerView i call (child)RecyclerView.scrollToPosition(scrollPosition).
And that's make the job
Parent RecyclerViewAdapter :
public class ProfilesCardViewListAdapter extends RecyclerView.Adapter<ProfilesCardViewListAdapter.ItemRowHolder> {
private ArrayList<AidodysProfile> sectionsList;
private Context context;
private boolean[] isShown;
private ProfileCardViewItemAdapter itemAdapters[];
public ProfilesCardViewListAdapter(ArrayList<AidodysProfile> sectionsList, Context context) {
this.sectionsList = sectionsList;
this.context = context;
this.isShown = new boolean[sectionsList.size()];
this.itemAdapters = new ProfileCardViewItemAdapter[sectionsList.size()];
for (int i = 0; i < sectionsList.size(); i++) {
this.isShown[i] = true;
this.itemAdapters[i] = new ProfileCardViewItemAdapter(sectionsList.get(i).getProfiles(), context, this);
}
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_card_view_horizontal, null);
final ItemRowHolder rowHolder = new ItemRowHolder(view);
rowHolder.itemRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
return rowHolder;
}
#Override
public void onBindViewHolder(final ItemRowHolder holder, final int position) {
String sectionName = sectionsList.get(position).getName();
AidodysProfile[] sectionItems = sectionsList.get(position).getProfiles();
holder.sectionTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_section_title));
holder.sectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showHideSection(holder, position);
}
});
if (isShown[position]) {
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
} else {
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
}
if (!sectionsList.get(position).isLeaf()) { // FOLDER
if (sectionName.equals("")) {
holder.sectionTitle.setVisibility(View.GONE);
holder.sectionButton.setVisibility(View.GONE);
} else {
holder.sectionTitle.setVisibility(View.VISIBLE);
holder.sectionButton.setVisibility(View.VISIBLE);
}
holder.sectionTitle.setText(sectionName);
} else { // PROFILE
return;
}
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setAdapter(itemAdapters[position]);
holder.itemRecyclerView.scrollToPosition(itemAdapters[position].getScrollPos());
}
private void showHideSection(ItemRowHolder holder, int position) {
if (holder.itemRecyclerView.getVisibility() == View.VISIBLE) {
isShown[position] = false;
holder.itemRecyclerView.setVisibility(View.GONE);
holder.sectionButton.setText(context.getText(R.string.action_profiles_section_show));
} else {
isShown[position] = true;
holder.itemRecyclerView.setVisibility(View.VISIBLE);
holder.sectionButton.setText(context.getString(R.string.action_profiles_section_hide));
}
}
#Override
public int getItemCount() {
return (sectionsList != null ? sectionsList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView sectionTitle;
protected RecyclerView itemRecyclerView;
protected Button sectionButton;
public ItemRowHolder(View view) {
super(view);
this.sectionTitle = (TextView) view.findViewById(R.id.section_title);
this.itemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view);
this.sectionButton = (Button) view.findViewById(R.id.section_button);
}
}
}
Child RecyclerViewAdapter :
class ProfileCardViewItemAdapter extends RecyclerView.Adapter<ProfileCardViewItemAdapter.SingleItemRowHolder> {
private AidodysProfile[] itemsList;
private CurrentUser currentUser;
private Context context;
private int scrollPos = 0;
private ProfilesCardViewListAdapter parent;
public int getScrollPos() {
return scrollPos;
}
public ProfileCardViewItemAdapter(AidodysProfile[] itemsList, Context context, ProfilesCardViewListAdapter parent) {
this.itemsList = itemsList;
this.context = context;
this.parent = parent;
this.currentUser = CurrentUser.getInstance(context);
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_view_horizontal, null);
SingleItemRowHolder rowHolder = new SingleItemRowHolder(view);
return (rowHolder);
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
AidodysProfile profile = itemsList[position];
holder.itemCardView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
scrollPos = position;
return false;
}
});
holder.itemCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectProfile(holder, position);
}
});
if (profile.getId() == currentUser.getProfile().getId()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemCardView.setCardBackgroundColor(context.getColor(R.color.white));
} else {
holder.itemCardView.setCardBackgroundColor(context.getResources().getColor(R.color.white));
}
}
holder.itemTitle.setText(profile.getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemPicture.setImageDrawable(context.getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.button1.setImageDrawable(context.getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getDrawable(R.drawable.ic_look_profile));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.itemTitle.setTextAppearance(R.style.Aidodys_Text_ProfilesList_Item);
holder.itemPicture.setColorFilter(context.getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getColor(R.color.aidodysRed));
} else {
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
} else {
holder.button1.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_edit_black_24dp));
holder.button2.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_look_profile));
holder.itemTitle.setTextColor(context.getResources().getColor(R.color.white));
holder.itemTitle.setTextSize(context.getResources().getDimension(R.dimen.text_size_profileslist_item));
holder.itemPicture.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_sheet_smile_black_48dp));
holder.itemPicture.setColorFilter(context.getResources().getColor(R.color.white));
holder.topParts.setBackgroundColor(context.getResources().getColor(R.color.aidodysRed));
}
}
private void selectProfile(SingleItemRowHolder holder, int position) {
SharedPreferences.Editor editor = context.getSharedPreferences("Aidodys", 0).edit();
editor.putString("profile", new Gson().toJson(itemsList[position]));
editor.apply();
currentUser.setProfile(itemsList[position]);
parent.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return (itemsList != null ? itemsList.length : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected ImageView itemPicture;
protected CardView itemCardView;
protected ImageView button1;
protected ImageView button2;
protected LinearLayout topParts;
public SingleItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView)view.findViewById(R.id.item_title);
this.itemPicture = (ImageView)view.findViewById(R.id.item_picture);
this.itemCardView = (CardView)view.findViewById(R.id.card_view_list_item);
this.topParts = (LinearLayout)view.findViewById(R.id.card_view_list_item_top_part);
this.button1 = (ImageView)view.findViewById(R.id.item_button_1);
this.button2 = (ImageView)view.findViewById(R.id.item_button_2);
}
}
}

Setting up a click listener on a button within a RecycleView

I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
I have done the same in this project, go here and copy this itemclicklistener class:
https://github.com/isaacurbina/MyMovies/blob/c985f28311f25522c7907d090e48dab5fc108c01/app/src/main/java/com/mobileappsco/training/mymovies/Listeners/RecyclerItemClickListener.java
Then on your Activity or Fragment do this with your recyclerview object.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// HERE GOES YOUR CODE FOR THE CLICK OF THE ITEM
}
})
);
Then you can use the position to reference the original object inside the list of objects that your adapter is using (the list should be public so that you can access it from the Activity or Fragment), or do like me and put a hidden textview with the ID instead of the position that you can get with:
TextView clickedItem = (TextView) view.findViewById(R.id.hidden_id_textview);
int id = clickedItem.getText();
You can also check at the whole project that contains the class that I sent you in the link above. I hope it helps.
Kind regards!

Categories

Resources