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());
}
}
Related
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);
}
}
}
I am using Recyclerview with multiple ViewTypes.I have two Model classes for two different type of item in recyclerview as.I want to display two different type of item in same RecyclerView
My RecyclerViewAdapter is
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
ArrayList<OneView> oneList;
ArrayList<TwoView> twoList;
public RecyclerAdapter(Context context,ArrayList<OneView> oneList,ArrayList<TwoView> twoList){
this.context=context;
this.oneList=oneList;
this.twoList=twoList;
}
#Override
public int getItemViewType(int position) {
switch (position){
case 0:
return 0;
case 1:
return 1;
}
return -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout=0;
RecyclerView.ViewHolder viewHolder;
if(viewType==0){
layout=R.layout.oneview;
View one= LayoutInflater.from(parent.getContext()).inflate(layout,parent,false);
return new ViewHolder(one);
}else if(viewType==1){
layout=R.layout.twoview;
View two= LayoutInflater.from(parent.getContext()).inflate(layout,parent,false);
return new SecondView(two);
}else {
return null;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType=holder.getItemViewType();
switch (viewType){
case 0:
OneView oneView=oneList.get(position);
((ViewHolder)holder).name.setText(oneView.getName());
break;
case 1:
TwoView twoView=twoList.get(position);
((SecondView)holder).name.setText(twoView.getName());
((SecondView)holder).address.setText(twoView.getAddress());
break;
default:
break;
}
}
#Override
public int getItemCount() {
return (this.oneList.size()+this.twoList.size());
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
public ViewHolder(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nameOne);
}
}
public class SecondView extends RecyclerView.ViewHolder {
private TextView name,address;
public SecondView(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nameTwo);
address=(TextView)itemView.findViewById(R.id.address);
}
}
}
I want to display two type of item in same RecyclerView.But I am getting Attempt to write to field 'int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a null object reference exception. How to resolve this ?
here is the complete example. I've used a RecyclerView with Multiple View Type. My scenario was, I have to show "cuisine list" [which is a horizontal view of multiple cuisines], then "number of restaurant", then "restaurant list".
so, i've used VIEW_RESTAURANT for restaurant view, VIEW_CUISINE for cuisine, VIEW_INFO for number of restaurant. As for my case, there's pagination, so VIEW_PROGRESS is used for showing progress bar at the bottom [by that time new set of data is fetch, if avaiable], VIEW_NO_DATA is used if restaurant list is empty.
hopefully from here, You can manage based on your requirement.
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private String TAG = HomeAdapter.class.getSimpleName();
class ViewType {
int VIEW_PROGRESS = 1;
int VIEW_NO_DATA = 2;
int VIEW_RESTAURANT = 3;
int VIEW_CUISINE = 4;
int VIEW_INFO = 6;
}
private ViewType mViewType = new ViewType();
private Context mContext;
private int mCuisineItem = 1;
private int mInfoItem = 1;
private int mShowNoItem = 0;
private boolean mIsLoading;
private int mRestaurantNumber;
private int mCurrentPage;
private List<Data> mDataList;
private List<CuisineData> mCuisines;
private PaginationListener mPaginationListener;
private HorizontalPaginationListener mHorizontalPaginationListener;
private SearchResultClickListener mSearchResultClickListener;
private String mFrom;
public HomeAdapter(Context context, List<Data> dataList, List<CuisineData> cuisines, RecyclerView recyclerView, SearchResultClickListener searchResultClickListener) {
mContext = context;
mDataList = dataList;
mCuisines = cuisines;
mSearchResultClickListener = searchResultClickListener;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager llManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visible_threshold = 1;
int total_item_count = llManager.getItemCount();
int last_visible_item = llManager.findLastVisibleItemPosition();
if (!mIsLoading && total_item_count <= (last_visible_item + visible_threshold)) {
if (mPaginationListener != null) mPaginationListener.onPagination();
mIsLoading = true;
}
}
});
}
}
public void setmPaginationListener(PaginationListener paginationListener) {
mPaginationListener = paginationListener;
}
public void setmHorizontalPaginationListener(HorizontalPaginationListener horizontalPaginationListener) {
mHorizontalPaginationListener = horizontalPaginationListener;
}
public void setLoaded() {
mIsLoading = false;
}
public void setmRestaurantNumber(int restaurantNumber) {
mRestaurantNumber = restaurantNumber;
}
public void setmCurrentPage(int currentPage) {
mCurrentPage = currentPage;
}
public void addCuisine(String from) {
mFrom = from;
notifyDataSetChanged();
}
public void addCuisines(List<CuisineData> cuisines, String from) {
mFrom = from;
mCuisines.clear();
mCuisines = cuisines;
notifyDataSetChanged();
}
public void addRestaurants(List<Data> dataList) {
mShowNoItem = 0;
if(mCurrentPage == 1) notifyItemChanged(1);
if (mCurrentPage == 1) notifyItemChanged(2);
int insert_index = mDataList.size();
int pos_start = insert_index + mCuisineItem + mInfoItem;
mDataList.addAll(insert_index, dataList);
notifyItemRangeInserted(pos_start, dataList.size());
}
public void removeRestaurants() {
mShowNoItem = 1;
mDataList.clear();
mDataList = new ArrayList<>();
notifyItemRangeRemoved(mCuisineItem + mInfoItem, mDataList.size());
notifyItemChanged(2);
}
public void addProgressBar(Data data) {
mDataList.add(data);
notifyItemInserted(getItemCount() - 1);
}
public void removeProgressBar() {
if (mDataList.size() > 0) {
mDataList.remove(mDataList.size() - 1);
notifyItemRemoved(mCuisineItem + mInfoItem + mDataList.size());
}
}
public void removeAll() {
mDataList.clear();
mCuisines.clear();
mShowNoItem = 0;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mDataList.size() + mShowNoItem + mCuisineItem + mInfoItem;
}
#Override
public int getItemViewType(int position) {
if (position == 0) return mViewType.VIEW_CUISINE;
if (position == 1) return mViewType.VIEW_INFO;
return mShowNoItem == 0 ? (mDataList.get(position - (mCuisineItem + mInfoItem)) != null ? mViewType.VIEW_RESTAURANT : mViewType.VIEW_PROGRESS)
: mViewType.VIEW_NO_DATA;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == mViewType.VIEW_CUISINE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal_cuisines, parent, false);
return new ViewHolderCuisinesList(mContext, view, mHorizontalPaginationListener);
}
if (viewType == mViewType.VIEW_INFO) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_restaurant_number, parent, false);
return new ViewHolderRestaurantNumber(mContext, view);
}
if (mShowNoItem == 0) {
if (viewType == mViewType.VIEW_RESTAURANT) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_item_nearest_restaurant, parent, false);
return new ViewHolderRestaurant(mContext, view, mSearchResultClickListener);
} else if (viewType == mViewType.VIEW_PROGRESS) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_progress, parent, false);
return new ViewHolderProgress(view);
}
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty, parent, false);
return new ViewHolderEmpty(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolderSearch) {
((ViewHolderSearch) holder).onBind();
}
if (holder instanceof ViewHolderCuisinesList) {
if (!TextUtils.isEmpty(mFrom)) {
if (mFrom.equalsIgnoreCase(AppConstants.CUISINES))
((ViewHolderCuisinesList) holder).onBind(mCuisines);
else if (mFrom.equalsIgnoreCase(AppConstants.CUISINE))
((ViewHolderCuisinesList) holder).onBind_();
}
}
if (holder instanceof ViewHolderRestaurantNumber) {
((ViewHolderRestaurantNumber) holder).onBind(mRestaurantNumber);
}
if (mShowNoItem == 0) {
if (holder instanceof ViewHolderRestaurant) {
((ViewHolderRestaurant) holder).onBind(position - (mCuisineItem + mInfoItem), mDataList.get(position - (mCuisineItem + mInfoItem)));
} else if (holder instanceof ViewHolderProgress) {
((ViewHolderProgress) holder).onBind();
}
} else {
if (holder instanceof ViewHolderEmpty) {
((ViewHolderEmpty) holder).onBind(mContext.getString(R.string.no_result_found));
}
}
}
}
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.
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 ?
I am implementing sticky header with RecyclerView. I have three sections (i.e 3 sticky headers) and they are working fine.Now I have taken three arraylists inside each section, I have initialized these list in my adapter and I am trying to get data of these lists on basis of header id inside onBindViewHolder. But it is not giving me the full list,just one string from each list (i.e under first section--data on first position of mylist,,,under second section-- data on second position of mylist1 ---under third section-- data on third position of mylist2)
Please Help !!
Code in Context:
StickyTestAdapter
public class StickyTestAdapter extends RecyclerView.Adapter<StickyTestAdapter.ViewHolder> implements
StickyHeaderAdapter<StickyTestAdapter.HeaderHolder> {
private Context mContext;
private ArrayList<String> mylist;
private ArrayList<String> mylist1;
private ArrayList<String> mylist2;
private static int countposition;
private String HEADER_FIRIST="HEADER_FIRIST";
private String HEADER_SECOND="HEADER_SECOND";
private String HEADER_THIRD="HEADER_THIRD";
public StickyTestAdapter(Context context) {
prepareData();
prepareData1();
prepareData2();
this.mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.item_test, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
long rowType= getHeaderId(position);
Log.e("getHeaderId----",""+rowType);
if (rowType==0){
if(!mylist.equals(""))
{
Log.e("list_data----", "" + mylist.get(position));
viewHolder.item.setText(mylist.get(position));
}
else
{
Log.e("Error--0--", "" + "error");
}
} else if (rowType==1){
if(!mylist1.equals(""))
{
Log.e("list_data1----", "" + mylist1.get(position));
viewHolder.item.setText(mylist1.get(position));
}
else
{
Log.e("Error---1-", "" + "error");
}
} else if (rowType==2){
if(!mylist2.equals(""))
{
Log.e("list_data2----", "" + mylist2.get(position));
viewHolder.item.setText(mylist2.get(position));
}
else
{
Log.e("Error----2", "" + "error");
}
}
}
#Override
public int getItemCount() {
if (getHeaderId(countposition)==0){
Log.e("mylist",""+mylist.size());
return mylist.size();
}else if (getHeaderId(countposition)==1){
Log.e("mylist1",""+mylist1.size());
return mylist1.size();
}else if (getHeaderId(countposition)==2){
Log.e("mylist2",""+mylist2.size());
return mylist2.size();
}
return 0;
}
#Override
public long getHeaderId(int pos) {
return pos;
}
#Override
public HeaderHolder onCreateHeaderViewHolder(ViewGroup parent) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.header_test, parent, false);
return new HeaderHolder(view);
}
#Override
public void onBindHeaderViewHolder(HeaderHolder viewholder, int count) {
countposition=count;
if (getItemViewType(count)==0){
viewholder.headertext.setText(HEADER_FIRIST);
}else if (getItemViewType(count)==1){
viewholder.headertext.setText(HEADER_SECOND);
}else if (getItemViewType(count)==2){
viewholder.headertext.setText(HEADER_THIRD);
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
item = (TextView)itemView.findViewById(R.id.text_item);
}
}
static class HeaderHolder extends RecyclerView.ViewHolder {
public TextView headertext;
public HeaderHolder(View itemView) {
super(itemView);
headertext = (TextView)itemView.findViewById(R.id.header_text);
}
}
#Override
public int getItemViewType(int position) {
return position;
}
public void prepareData()
{
mylist=new ArrayList<>();
mylist.add("rajendra");
mylist.add("rani");
mylist.add("rahul");
}
public void prepareData1()
{
mylist1=new ArrayList<>();
mylist1.add("ravi");
mylist1.add("vikram");
mylist1.add("rakesh");
}
public void prepareData2()
{
mylist2=new ArrayList<>();
mylist2.add("apple");
mylist2.add("ashok");
mylist2.add("vikash");
}
}
Question is quite old. But that code looks complicated to read, personally I try to not reinvent what others did quite well by creating libraries.
GitHub is full of source that you can import. Some examples: FlexibleAdapter, FastAdapter, Epoxy and others.
I have build the first one, but you can try the others as well.
With mine, having multiple views and headers with sections is quite easy, I point here the wiki page where I define the section and how to initialize it.
Along with this feature, you have a lot more functionalities that makes your life easier.
I divide arraylist into 3 section based on alphabet like contactlist.
For that i use SectionedRecyclerViewAdapter
MainActivity.java
public class MainActivity extends AppCompactActivity {
private SectionedRecyclerViewAdapter sectionAdapter;
#Override
public View onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
sectionAdapter = new SectionedRecyclerViewAdapter();
for(char alphabet = 'a'; alphabet <= 'z';alphabet++) {
List<String> contacts = getContactsWithLetter(alphabet);
if (contacts.size() > 0) {
sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
return view;
}
#Override
public void onResume() {
super.onResume();
if (getActivity() instanceof AppCompatActivity) {
AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity.getSupportActionBar() != null)
activity.getSupportActionBar().setTitle(R.string.nav_example1);
}
}
private List<String> getContactsWithLetter(char letter) {
List<String> contacts = new ArrayList<>();
for (String contact : getResources().getStringArray(R.array.names_)) {
if (contact.charAt(0) == letter) {
contacts.add(contact);
}
}
return contacts;
}
private class ContactsSection extends StatelessSection {
String title;
List<String> list;
ContactsSection(String title, List<String> list) {
super(new SectionParameters.Builder(R.layout.section_ex1_item)
.headerResourceId(R.layout.section_ex1_header)
.build());
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size();
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return new ItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
String name = list.get(position);
itemHolder.tvItem.setText(name);
itemHolder.imgItem.setImageResource(name.hashCode() % 2 == 0 ? R.drawable.ic_face_black_48dp : R.drawable.ic_tag_faces_black_48dp);
itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), String.format("Clicked on position #%s of Section %s", sectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
private final TextView tvTitle;
HeaderViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
}
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final ImageView imgItem;
private final TextView tvItem;
ItemViewHolder(View view) {
super(view);
rootView = view;
imgItem = (ImageView) view.findViewById(R.id.imgItem);
tvItem = (TextView) view.findViewById(R.id.tvItem);
}
}
}
use structure similar to
public class MultiArray<T> {
List<ItemGroup> lists = new ArrayList<>();
public void addList(String headerText, List<T> list) {
lists.add(new ItemGroup(headerText, list));
}
public int itemCount() {
int count = 0;
for (ItemGroup group : lists) {
count += group.count();
}
return count;
}
public T getItem(int position) {
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.item(position - count);
}
count += group.count();
}
return null;
}
public int getGroupIndex(int position) {
int count = 0;
int groupIndex = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return groupIndex;
}
count += group.count();
groupIndex++;
}
return -1;
}
public String getHeaderText(int position){
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.headerText;
}
count += group.count();
}
return "";
}
class ItemGroup {
public final String headerText;
public final List<T> list;
public ItemGroup(String headerText, List<T> list) {
this.headerText = headerText;
this.list = list;
}
public int count() {
return list.size();
}
public T item(int position) {
return list.get(position);
}
}
}
you can optimize it for faster performance