Retrieving wrong a negative adapter position - android

i use the code below to populate a recycler view containing image views and it works perfectly
public class PopularImageAdapter extends RecyclerView.Adapter<PopularImageAdapter.PhotoViewHolder> {
private static final int PHOTO_ANIMATION_DELAY = 600;
private static final Interpolator INTERPOLATOR = new DecelerateInterpolator();
private List<FeedItem> feedItems;
private Context context;
private final int cellSize;
private int lastAnimatedItem = -1;
private boolean lockedAnimations = false;
private OnPhotoFeedItemClickListener onFeedItemClickListener;
public PopularImageAdapter(Context context, List<FeedItem> feedItems){
this.context = context;
this.feedItems = feedItems;
this.cellSize = Utils.getScreenWidth(context) / 3;
}
#NonNull
#Override
public PopularImageAdapter.PhotoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false);
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
layoutParams.height = cellSize;
layoutParams.width = cellSize;
layoutParams.setFullSpan(false);
view.setLayoutParams(layoutParams);
PhotoViewHolder cellFeedViewHolder = new PhotoViewHolder(view);
setupClickableViews(view,cellFeedViewHolder);
return new PhotoViewHolder(view);
}
private void setupClickableViews(final View view,final PhotoViewHolder cellFeedViewHolder) {
cellFeedViewHolder.ivPhoto.setOnClickListener(v -> onFeedItemClickListener.onPhotoClick(view, cellFeedViewHolder.getAdapterPosition(),feedItems));
}
#Override
public void onBindViewHolder(#NonNull PopularImageAdapter.PhotoViewHolder holder,final int position) {
holder.bindView(feedItems.get(position));
FeedItem item = feedItems.get(position);
Picasso.with(context)
.load(item.getImge())
.resize(cellSize, cellSize)
.centerCrop()
.into(holder.ivPhoto, new Callback() {
#Override
public void onSuccess() {
animatePhoto(holder);
}
#Override
public void onError() {
}
});
if (lastAnimatedItem < position) lastAnimatedItem = position;
}
private void animatePhoto(PhotoViewHolder viewHolder) {
if (!lockedAnimations) {
if (lastAnimatedItem == viewHolder.getAdapterPosition()) {
setLockedAnimations(true);
}
long animationDelay = PHOTO_ANIMATION_DELAY + viewHolder.getAdapterPosition() * 30;
viewHolder.flRoot.setScaleY(0);
viewHolder.flRoot.setScaleX(0);
viewHolder.flRoot.animate()
.scaleY(1)
.scaleX(1)
.setDuration(200)
.setInterpolator(INTERPOLATOR)
.setStartDelay(animationDelay)
.start();
}
}
public void setLockedAnimations(boolean lockedAnimations) {
this.lockedAnimations = lockedAnimations;
}
#Override
public int getItemCount() {
return feedItems.size();
}
public void setOnFeedItemClickListener(OnPhotoFeedItemClickListener onFeedItemClickListener) {
this.onFeedItemClickListener = onFeedItemClickListener;
}
public interface OnPhotoFeedItemClickListener {
void onPhotoClick(View v,int position, List<FeedItem> feedItems);
}
public static class PhotoViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.flRoot)
FrameLayout flRoot;
#BindView(R.id.ivPhoto)
ImageView ivPhoto;
FeedItem feedItem;
PhotoViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
void bindView(FeedItem feedItem){
this.feedItem = feedItem;
}
}
}
but when i use
#Override
public void onPhotoClick(View v,int position, List<FeedItem> feedItems) {
FeedItem item = feedItems.get(position);
String name = item.getName();
Toast.makeText(getContext(),name + "Is the name ", Toast.LENGTH_LONG).show();
}
i get an error showing that my adapterposition is -1 and i am not sure where the -1 comes from because even when i remove the global variable initialized to -1 i still get -1 as the adapter position

In your onCreateViewHolder method you're returning new instance of PhotoViewHolder instead of cellFeedViewHolder in which you have defined your clicks.

Related

When I Enable Slider in Adapter Last position not showing (SLIDER_VIEW merge with ITEM_VIEW )

Need to Show Slider With a missing fisrt position of ITEM_VIEW
Check IMAGE 1
When Slider Enabled Don't Showing first position of ITEM_VIEW (Issue is SLIDER_VIEW position merge with ITEM_VIEW position). Need to show ITEM_VIEW missing first position With Slider
Check IMAGE 2
When Slider Not Enabled ITEM_VIEW first position Showing
public class WallpapersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM_VIEW = 0;
private static final int AD_VIEW = 1;
private static final int SLIDER_VIEW = 2;
public static SharedPreferences sharedPreferences;
final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 6000; // time in milliseconds between successive task executions.
private final Context mContext;
private final OnItemClickListener listener;
private final int itemLayout;
public List<Image> mData;
RequestOptions option;
SharedPref sharedPref;
String status;
List<SliderUtils> sliderImg;
ViewPagerAdapterSlider viewPagerAdapterSlider;
int currentPage = 1;
Timer timer;
private int dotscount;
private ImageView[] dots;
public WallpapersAdapter(Context mContext, List<Image> mData, OnItemClickListener listener) {
this.mContext = mContext;
this.mData = mData;
this.listener = listener;
this.itemLayout = R.layout.wallpaper_item;
// Request option for Glide
option = new RequestOptions().centerCrop();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
if (viewType == ITEM_VIEW) {
View view = layoutInflater.inflate(R.layout.wallpaper_item, parent, false);
return new MainViewHolder(view);
} else if (viewType == AD_VIEW) {
View view = layoutInflater.inflate(R.layout.item_native_ad, parent, false);
return new AdViewHolder(view);
} else if (viewType == SLIDER_VIEW) {
View view = layoutInflater.inflate(R.layout.custom_layout, parent, false);
return new SliderViewHolder(view);
} else {
return null;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
status = sharedPreferences.getString("status", "free");
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
if (holder.getItemViewType() == ITEM_VIEW) {
int pos = position - Math.round(position / Config.NATIVE_ADS_PER_ITEM);
((MainViewHolder) holder).bindData(mData.get(pos), listener, position);
} else if (holder.getItemViewType() == AD_VIEW) {
if (Config.ENABLE_ADS == true & status.equals("free")) {
((AdViewHolder) holder).bindAdData();
layoutParams.setFullSpan(getItemViewType(position) == AD_VIEW);
}
} else if (holder.getItemViewType() == SLIDER_VIEW) {
layoutParams.setFullSpan(getItemViewType(position) == SLIDER_VIEW);
((SliderViewHolder) holder).bindSliderData();
}
}
#Override
public int getItemCount() {
if (mData.size() > 0) {
return mData.size() + Math.round(mData.size() / Config.NATIVE_ADS_PER_ITEM);
}
return mData.size();
}
#Override
public int getItemViewType(int position) {
// Here position set 0 showing Slider But not showing last position
if ((position == 0) && Config.ENABLE_RECENT_SLIDER == true) {
return SLIDER_VIEW;
} else if ((position + 1) % Config.NATIVE_ADS_PER_ITEM == 0) {
return AD_VIEW;
}
return ITEM_VIEW;
}
private void sendRequest(ViewPager viewPagerForSlider, TextView textSlider) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Config.SM, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja_data = response.getJSONArray("slides");
Log.d("OHOHOH", String.valueOf(ja_data));
for (int i = 0; i < ja_data.length(); i++) {
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = ja_data.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("slider_image"));
sliderUtils.setUrl(jsonObject.getString("url"));
sliderUtils.setSlider_name(jsonObject.getString("slider_name"));
sliderUtils.setType(jsonObject.getString("slider_type"));
sliderUtils.setCat_id(jsonObject.getInt("cat_id"));
sliderUtils.setCollection(jsonObject.getString("collection"));
//textSlider.setText(jsonObject.getString("slider_name"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapterSlider = new ViewPagerAdapterSlider(sliderImg, mContext);
viewPagerForSlider.setAdapter(viewPagerAdapterSlider);
dotscount = viewPagerAdapterSlider.getCount();
dots = new ImageView[dotscount];
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == dotscount) {
currentPage = 0;
}
viewPagerForSlider.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MySingleton.getInstance(mContext).addToRequestQueue(request);
}
public interface OnItemClickListener {
void onItemClick(View view, Image mData, int position);
}
public class MainViewHolder extends RecyclerView.ViewHolder {
WallpaperItemBinding binding;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
binding = WallpaperItemBinding.bind(itemView);
}
public void bindData(Image main, final OnItemClickListener listener, final int position) {
sharedPref = new SharedPref(mContext);
binding.wallpaperName.setText(main.getImage_name());
binding.viewCount.setText(main.getViews_count());
if (sharedPref.loadAmoled() == true) {
binding.constraintBg.setBackgroundColor(mContext.getResources().getColor(R.color.amoled_color_light));
}
sharedPref = new SharedPref(mContext);
}
}
public class AdViewHolder extends RecyclerView.ViewHolder {
ItemNativeAdBinding binding;
public AdViewHolder(#NonNull View itemView) {
super(itemView);
binding = ItemNativeAdBinding.bind(itemView);
}
#SuppressLint("MissingPermission")
private void bindAdData() {
final AdLoader adLoader = new AdLoader.Builder(mContext, mContext.getResources().getString(R.string.admob_native_id))
.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
#Override
public void onNativeAdLoaded(NativeAd ad) {
binding.admobNativeAdContainer.setNativeAd(ad);
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(), 3);
if (isNetworkConnected()) {
binding.admobNativeAdContainer.setVisibility(View.VISIBLE);
}
}
#SuppressLint("MissingPermission")
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
}
public class SliderViewHolder extends RecyclerView.ViewHolder {
CustomLayoutBinding customLayoutBinding;
public SliderViewHolder(View view) {
super(view);
customLayoutBinding = CustomLayoutBinding.bind(view);
}
public void bindSliderData() {
sliderImg = new ArrayList<>();
customLayoutBinding.viewPagerForSlider.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
customLayoutBinding.dotsIndicator.setViewPager(customLayoutBinding.viewPagerForSlider);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
sendRequest(customLayoutBinding.viewPagerForSlider, customLayoutBinding.textSlider);
}
}
}

Dynamic header in grid view android

i want to sort my photos according to date and display them in a grid layout using grid layout manager in recycler view like attached picture but i dont know how to do this.i want this type of view after sorting
i added header but at fix index ,dynamically how to do this ?because when we don't know how many photos are there in a specific date so it is not possible to add header in photos list at that specific index.
MyPhotoListAdapter.java
public class MYPhotoListAdapter extends RecyclerView.Adapter {
private List<PhotoInfo> mSelectList;
private List<PhotoInfo> list;
private int mScreenWidth;
private int mRowWidth;
private Activity mActivity;
private List generalList;
public final int HEADER_TYPE=1;
public final int OTHER_TYPE=2;
public MYPhotoListAdapter(Activity activity, List<PhotoInfo> list, List<PhotoInfo> selectList, int screenWidth) {
this.mSelectList = selectList;
this.mScreenWidth = screenWidth;
this.mRowWidth = mScreenWidth / 3;
this.list=list;
this.mActivity = activity;
generalList=list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case HEADER_TYPE:
View headerview = LayoutInflater.from(parent.getContext()).inflate(R.layout.textheader_layout,null);
return new textViewHolder(headerview);
default:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gf_adapter_photo_list_item,null);
setHeight(view);
return new viewHolder(view);
}
}
private void setHeight(final View convertView) {
int height = mScreenWidth / 3 - 8;
convertView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(position==0){
return;
}
PhotoInfo photoInfo = (PhotoInfo) generalList.get(position);
String path = "";
if (photoInfo != null) {
path = photoInfo.getPhotoPath();
}
((viewHolder)holder).mIvThumb.setImageResource(R.drawable.ic_gf_default_photo);
Drawable defaultDrawable = mActivity.getResources().getDrawable(R.drawable.ic_gf_default_photo);
GalleryFinal.getCoreConfig().getImageLoader().displayImage(mActivity, path, ((viewHolder)holder).mIvThumb, defaultDrawable, mRowWidth, mRowWidth);
((viewHolder)holder).mView.setAnimation(null);
if (GalleryFinal.getCoreConfig().getAnimation() > 0) {
((viewHolder)holder).mView.setAnimation(AnimationUtils.loadAnimation(mActivity, GalleryFinal.getCoreConfig().getAnimation()));
}
((viewHolder)holder).mIvCheck.setImageResource(R.drawable.ic_check_image);
if (GalleryFinal.getFunctionConfig().isMutiSelect()) {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
if (mSelectList.contains(photoInfo)) {
((viewHolder)holder).mIvCheck.setVisibility(View.VISIBLE);
// holder.mIvCheck.setBackgroundColor(GalleryFinal.getGalleryTheme().getCheckSelectedColor());
} else {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
// holder.mIvCheck.setBackgroundColor(GalleryFinal.getGalleryTheme().getCheckNornalColor());
}
} else {
((viewHolder)holder).mIvCheck.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return generalList.size();
}
#Override
public int getItemViewType(int position) {
return position==0?HEADER_TYPE:OTHER_TYPE;
}
public class viewHolder extends RecyclerView.ViewHolder{
public GFImageView mIvThumb;
public ImageView mIvCheck;
View mView;
public viewHolder(View itemView) {
super(itemView);
mView = itemView;
mIvThumb = (GFImageView) itemView.findViewById(R.id.iv_thumb);
mIvCheck = (ImageView) itemView.findViewById(R.id.iv_check);
}
}
public class textViewHolder extends RecyclerView.ViewHolder{
TextView textView;
public textViewHolder(View itemView) {
super(itemView);
textView=new TextView(itemView.getContext());
}
}
}
Activity.java
final GridLayoutManager glm=new GridLayoutManager(this,5);
mGvPhotoList.setLayoutManager(glm);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return position==0?glm.getSpanCount():1;
}
});
myPhotoListAdapter=new MYPhotoListAdapter(this, mCurPhotoList, mSelectPhotoList, mScreenWidth);
mGvPhotoList.setAdapter(myPhotoListAdapter);
this code is working but here i'm adding header on fixed index but i wan't it dynamically for each specific date .
PhotoInfo.java
public class PhotoInfo implements Serializable {
private int photoId;
private String photoPath;
//private String thumbPath;
private int width;
private int height;
private String photoDate;
public PhotoInfo() {
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
public int getPhotoId() {
return photoId;
}
public void setPhotoId(int photoId) {
this.photoId = photoId;
}
//
//public String getThumbPath() {
// return thumbPath;
//}
//
//public void setThumbPath(String thumbPath) {
// this.thumbPath = thumbPath;
//}
public String getPhotoDate() {
return photoDate;
}
public void setPhotoDate(String photoDate) {
this.photoDate = photoDate;
}
#Override
public boolean equals(Object o) {
if (o == null || !(o instanceof PhotoInfo)) {
return false;
}
PhotoInfo info = (PhotoInfo) o;
if (info == null) {
return false;
}
return TextUtils.equals(info.getPhotoPath(), getPhotoPath());
}
}

How to expand the RecyclerView items?

I have alot of ImageViews in RecyclerView item in LinearLayout. When I scroll horizontally it scrolls perfectly. But I want the focused item in RecyclerView to get expanded from the actual size.
Any help ?
public class NavigationBarManager extends RecyclerView.Adapter<NavigationBarManager.FilterItemHolder> implements OnItemSelectedListener, AnimatorListener{//, Observer {
private static final String TAG = "NavigationBarManager";
private RecyclerView mRecyclerView ;
private int mSelectedItem = 0;
private NotificationHandler mAnimNtfHandler;
public static final int DIRECTION_LEFT = -1;
public static final int DIRECTION_RIGHT = 1;
Context mContext;
FilterItemHolder mFilterItemHolder;
private ArrayList<String> mFilterStringList;
private ArrayList<Drawable> mFilterDrawableList;
private ArrayList<Integer> mCursorIdxList;
private ArrayList<Integer> mFilterIdList;
private HtvChannelListUtil mListUtil;
private ITvSettingsManager mSettings;
private RecyclerView.SmoothScroller smoothScroller;
private LinearLayoutManager mRecyclerViewMgr = null;
public NavigationBarManager(Context context)
{
mContext = context;
mAnimNtfHandler = NotificationHandler.getInstance();
mFilterStringList = new ArrayList<String>();
mFilterDrawableList = new ArrayList<Drawable>();
mFilterIdList = new ArrayList<Integer>();
mCursorIdxList = new ArrayList<Integer>();
mListUtil = HtvChannelListUtil.getInstance();
mSettings = ITvSettingsManager.Instance.getInterface();
mCacheManager = HtvChannelCacheManager.getInstance();
mFillDataIntoNavigationBar();
mNtfHandler = NotificationHandler.getInstance();
}
public void setLayoutManager(LinearLayoutManager pRecyclerViewMgr)
{
mRecyclerViewMgr = pRecyclerViewMgr;
}
public class FilterItemHolder extends RecyclerView.ViewHolder
{
ImageView imageView;
//ImageView mBgView;
public FilterItemHolder(View itemView)
{
super(itemView);
// get the reference of item view's
imageView=(ImageView) itemView.findViewById(R.id.imageview);
//mBgView = (ImageView) itemView.findViewById(R.id.bgView);
}
}
#Override
public FilterItemHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
Log.e(TAG,"onCreateViewHolder viewType" +viewType);
View lViewHolder = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
FilterItemHolder lHolder = new FilterItemHolder(lViewHolder);
mFilterItemHolder = lHolder;
return lHolder;
}
#Override
public void onBindViewHolder(FilterItemHolder holder, final int position)
{
Log.e(TAG,"onBindViewHolder position=" +position);
Log.e(TAG,"onBindViewHolder getAdapterPosition=" +holder.getAdapterPosition());
Log.e(TAG,"mSelectedItem=" +mSelectedItem);
holder.imageView.setImageDrawable(mFilterDrawableList.get(position));
if(position == mSelectedItem)
{
holder.imageView.requestFocus();
holder.imageView.setSelected(true);
Log.e(TAG,"requesting focus=");
//holder.mBgView.setBackgroundResource(R.drawable.button_box_hil);
}
else
{
holder.imageView.setSelected(false);
//holder.mBgView.setBackgroundResource(0);
}
}
#Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
}
#Override
public void onItemSelected(AdapterView<?> pParent, View pView, int pPosition, long pId)
{
Log.d(TAG,"onItemSelected " + pPosition);
}
#Override
public int getItemCount()
{
return mFilterDrawableList.size();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
Log.e(TAG,"onNothingSelected");
}
#Override
public void onAnimationCancel(Animator pAnimator)
{
}
#Override
public void onAnimationEnd(Animator pAnimator)
{
}
#Override
public void onAnimationRepeat(Animator pAnimator)
{
}
#Override
public void onAnimationStart(Animator pAnimator)
{
}
public void moveFocus(int pDirection)
{
int lNextSelect = mSelectedItem + pDirection;
if (lNextSelect >= 0 && lNextSelect < getItemCount())
{
//notifyItemChanged(mSelectedItem);
mSelectedItem = lNextSelect;
//notifyItemChanged(mSelectedItem);
mRecyclerView.smoothScrollToPosition(mSelectedItem);
if(mRecyclerView.getChildAt(mSelectedItem) != null)
{
//mRecyclerView.getChildAt(mSelectedItem).requestFocus();
}
}
else
{
return;
}
setNavigatorText();
setCurrentSelection(mSelectedItem);
int lSelectedList = mCursorIdxList.get(mSelectedItem);
mCacheManager.setCurrentListIdx(lSelectedList);
mListUtil.selectList(lSelectedList);
mNtfHandler.notifyAllObservers(EventID.CH_LIST_REFRESH,null);
}
public void refresh()
{
mRecyclerView.smoothScrollToPosition(mSelectedItem);
int lCurrentList = mCacheManager.getCurrentListIdx();
int lNewSelection = mCursorIdxList.indexOf((Integer)lCurrentList);
Log.d(TAG,"refresh: old selection - "+ mSelectedItem + "new selection - " + lNewSelection);
if(mSelectedItem != lNewSelection)
{
//notifyItemChanged(mSelectedItem);
mSelectedItem = lNewSelection;
//notifyItemChanged(mSelectedItem);
if(mRecyclerView.getChildAt(mSelectedItem) != null)
{
mRecyclerView.getChildAt(mSelectedItem).requestFocus();
}
setNavigatorText();
setCurrentSelection(mSelectedItem);
}
}
}
The above code is my class which extends RecyclerView. Do I have to add some animator to expand the items. If yes where and how ?

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);
}
}
}

how can handle with recyclerview item with three options to choose

How can handle with this situation -> I have a list of itens in a recyclerView and I want to choose one of those option: green, yellow or red face to get the value of object from list item I chose
So I thought something like bellow, but when I select one of those faces anything happens. I think that button click listener doesn't work. Please someone can drive me to a better suggestion that works, give me an example or could me tell what am I doing wrong?
My adapter
public class LikeListAdapter extends RecyclerView.Adapter<LikeListAdapter.LikeItemViewHolder> {
private List<Goals> goalsList;
private SparseBooleanArray selectedItems;
public LikeListAdapter(List<Goals> goalsList) {
this.goalsList = goalsList;
}
#Override
public LikeItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.recycler_item_like, parent, false);
return new LikeItemViewHolder(view);
}
#Override
public void onBindViewHolder(LikeItemViewHolder holder, int position) {
final Goals goals = goalsList.get(position);
if (goals != null && getItemCount() > 0) {
holder.goalsDescriptionTextView.setText(goals.getDescription());
holder.happyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("fretgr", "get Green Point = " + goals.getGreenPoint());
setToggleSelection(1);
}
});
holder.sosoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("rtret", "get Yellow Point = " + goals.getYellowPoint());
setToggleSelection(2);
}
});
holder.angryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("ewwr", "get Red Point = " + goals.getRedPoint());
setToggleSelection(3);
}
});
}
}
#Override
public int getItemCount() {
return goalsList.size();
}
public class LikeItemViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.description_goalsTextView)
TextView goalsDescriptionTextView;
#Bind(R.id.happy)
ImageView happyButton;
#Bind(R.id.soso)
ImageView sosoButton;
#Bind(R.id.angry)
ImageView angryButton;
public LikeItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
// method to access in activity after updating selection
public List<Goals> getGoalsList() {
return goalsList;
}
public void setToggleSelection(int pointType){
selectedItems = new SparseBooleanArray();
if (selectedItems.get(pointType, false)) {
selectedItems.delete(pointType);
} else {
selectedItems.put(pointType, true);
}
notifyItemChanged(pointType);
}
public int getToggleSelection(){
return 0;
}
}
My Fragment
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.scrollToPosition(0);
assocGoalsRecyclerView.setLayoutManager(layoutManager);
assocGoalsRecyclerView.setHasFixedSize(true);
likeListAdapter = new LikeListAdapter(associateList);
assocGoalsRecyclerView.setAdapter(likeListAdapter);
assocGoalsRecyclerView.addOnItemTouchListener(RecycleTouchListener);
private RecyclerView.OnItemTouchListener RecycleTouchListener = new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = assocGoalsRecyclerView.findChildViewUnder(e.getX(), e.getY());
if(child!=null && mGestureDetector.onTouchEvent(e)){
final int position = assocGoalsRecyclerView.getChildAdapterPosition(child);
final Goals goals = associateList.get(position);
final Categories c = categoriesList.get(position);
final int type = likeListAdapter.getToggleSelection();
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
};
I found an answer based in another responses and sugestions!!! Android: handling clicks on image view inside recycler's view item using touch framework
In My Fragment
Snippet from fragment:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.scrollToPosition(0);
assocGoalsRecyclerView.setLayoutManager(layoutManager);
// assocGoalsRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
assocGoalsRecyclerView.setHasFixedSize(true);
likeListAdapter = new LikeListAdapter(associateList, onItemClickCallback);
assocGoalsRecyclerView.setAdapter(likeListAdapter);
public static class OnItemClickListener implements View.OnClickListener {
private int position;
private OnItemClickCallback onItemClickCallback;
public OnItemClickListener(int position, OnItemClickCallback onItemClickCallback) {
this.position = position;
this.onItemClickCallback = onItemClickCallback;
}
#Override
public void onClick(View view) {
onItemClickCallback.onItemClicked(view, position);
}
public interface OnItemClickCallback {
void onItemClicked(View view, int position);
}
}
private OnItemClickListener.OnItemClickCallback onItemClickCallback = new OnItemClickListener.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
switch(view.getId()){
case R.id.happy:
Log.e("rtetre", "happy assessed and position is = " + position);
break;
case R.id.soso:
Log.e("rwere", "soso assessed and position is = " + position);
break;
case R.id.angry:
Log.e("dfrefgt", "angry assessed and position is = " + position);
break;
}
}
};
In My adapter
public class LikeListAdapter extends RecyclerView.Adapter<LikeListAdapter.LikeItemViewHolder> {
private List<Goals> goalsList;
private LikeFragment.OnItemClickListener.OnItemClickCallback onItemClickCallback;
public LikeListAdapter(List<Goals> goalsList, LikeFragment.OnItemClickListener.OnItemClickCallback onItemClickCallback) {
this.goalsList = goalsList;
this.onItemClickCallback = onItemClickCallback;
}
#Override
public LikeItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.recycler_item_like, parent, false);
LikeItemViewHolder likeItemViewHolder = new LikeItemViewHolder(view);
return likeItemViewHolder;
}
#Override
public void onBindViewHolder(LikeItemViewHolder holder, int position) {
final Goals goals = goalsList.get(position);
if (goals != null && getItemCount() > 0) {
holder.goalsDescriptionTextView.setText(goals.getDescription());
holder.happyButton.setOnClickListener(new LikeFragment.OnItemClickListener(position, onItemClickCallback));
holder.sosoButton.setOnClickListener(new LikeFragment.OnItemClickListener(position, onItemClickCallback));
holder.angryButton.setOnClickListener(new LikeFragment.OnItemClickListener(position, onItemClickCallback));
}
}
#Override
public int getItemCount() {
return goalsList.size();
}
public static class LikeItemViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.description_goalsTextView)
TextView goalsDescriptionTextView;
#Bind(R.id.happy)
ImageView happyButton;
#Bind(R.id.soso)
ImageView sosoButton;
#Bind(R.id.angry)
ImageView angryButton;
public LikeItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}

Categories

Resources