I have 2 different layouts which I want to use for my views in specific situations in a Recycler View. the user decides which layout should appear. how is it possible to change the layout of my views which are being shown in the recycler view at run time? I think I need to force my adapter to restart and recreate and rearrange the views. how to do that at a way that I don't lose my insert animation?
UPDATE:
public class InfinityFragmentRecyclerAdapter extends RecyclerView.Adapter implements HasDatabase
{
protected JsonDatabase jsonDatabase = new JsonDatabase(null);
protected Context mContext;
protected int arrangeMode;
public InfinityFragmentRecyclerAdapter(Context context, int viewMode)
{
mContext = context;
arrangeMode = viewMode;
}
// this is the method which enables me to change the view mode
public void setNewArrangeMode(int mode)
{
arrangeMode = mode;
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View view;
if (arrangeMode == SupportsGridAndListArrangement.GRID_VIEW)
{
view = LayoutInflater.from(viewGroup.getContext()).inflate
(R.layout.grid_layout, null);
}
else
{
view = LayoutInflater.from(viewGroup.getContext()).inflate
(R.layout.list_layout, null);
}
return new ItemHolder(view, mContext, arrangeMode);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i)
{
....
if (arrangeMode == SupportsGridAndListArrangement.LIST_VIEW)
{
...
StaggeredGridLayoutManager.LayoutParams layoutParams =
new StaggeredGridLayoutManager.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
viewHolder.itemView.setLayoutParams(layoutParams);
}
}
#Override
public int getItemCount()
{
if (jsonDatabase != null)
{
return jsonDatabase.getCount();
}
else
{
return 0;
}
}
#Override
public Object getDatabase()
{
return jsonDatabase;
}
public void append(Object newJsonDatabase)
{
int currentCount = 0;
if (jsonDatabase != null)
{
currentCount = jsonDatabase.getCount();
}
int newCount = ((JsonDatabase) newJsonDatabase).getCount();
jsonDatabase.appendAtEnd((JsonDatabase) newJsonDatabase);
for (int i = currentCount; i < (currentCount + newCount); i++)
{
notifyItemInserted(i);
}
}
}
Related
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 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);
}
}
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i)
{
// below I put layout show hide logic.this logic working but when i scroll the layout disturb.
if (month_value.equalsIgnoreCase("") || !(month_value.equalsIgnoreCase(ci.monthgrpmore_str))) {
month_value = ci.monthgrpmore_str;
contactViewHolder.dfgnew.setVisibility(View.VISIBLE);
contactViewHolder.product_header2.setVisibility(View.VISIBLE);
} else {
contactViewHolder.dfgnew.setVisibility(View.GONE);
contactViewHolder.product_header2.setVisibility(View.GONE);
}
if (Global_Data.target_grpby.equalsIgnoreCase("By Product")) {
contactViewHolder.month_grpby.setText("Product Sub Category");
}
}
// I find answer of my problem just replace some code in onBindViewHolder
if (month_value.equalsIgnoreCase("") || !(month_value.equalsIgnoreCase(ci.monthgrpmore_str))) {
month_value = ci.monthgrpmore_str;
contactViewHolder.dfgnew.setVisibility(View.VISIBLE);
contactViewHolder.product_header2.setVisibility(View.VISIBLE);
} else {
contactViewHolder.dfgnew.setVisibility(View.GONE);
contactViewHolder.product_header2.setVisibility(View.GONE);
}
//replace above cobe with below code inside onBindViewHolder
if (i > 0 && !(contactList.get(i).monthgrpmore_str.equalsIgnoreCase(contactList.get(i-1).monthgrpmore_str))) {
month_value = ci.monthgrpmore_str;
contactViewHolder.dfgnew.setVisibility(View.VISIBLE);
contactViewHolder.product_header2.setVisibility(View.VISIBLE);
} else {
if(i != 0)
{
contactViewHolder.dfgnew.setVisibility(View.GONE);
contactViewHolder.product_header2.setVisibility(View.GONE);
}
}
// And my full adapter code is below.
public class GrpbyMore_Adapter extends RecyclerView.Adapter<GrpbyMore_Adapter.ContactViewHolder> {
int a=0;
String month_value = "";
private List<TargetValue_info> contactList;
private List<TargetValue_info> contactListnew;
public GrpbyMore_Adapter(List<TargetValue_info> contactList) {
this.contactList = contactList;
this.contactListnew = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i)
{
++a;
// if(a <= contactListnew.size()) {
TargetValue_info ci = contactList.get(i);
// if (contactViewHolder != null) {
contactViewHolder.setIsRecyclable(false);
contactViewHolder.prdcatg_more.setText(ci.prdcatg_morestr);
contactViewHolder.month_more.setText(ci.monthgrpmore_str);
if (month_value.equalsIgnoreCase("") || !(month_value.equalsIgnoreCase(ci.monthgrpmore_str))) {
month_value = ci.monthgrpmore_str;
contactViewHolder.dfgnew.setVisibility(View.VISIBLE);
contactViewHolder.product_header2.setVisibility(View.VISIBLE);
} else {
contactViewHolder.dfgnew.setVisibility(View.GONE);
contactViewHolder.product_header2.setVisibility(View.GONE);
}
if (Global_Data.target_grpby.equalsIgnoreCase("By Product")) {
contactViewHolder.month_grpby.setText("Product Sub Category");
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = null;
itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.summary2_adapter, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView prdcatg_more;
protected TextView month_more;
public ContactViewHolder(View v) {
super(v);
prdcatg_more = (TextView) v.findViewById(R.id.prdcatg_more);
month_grpby = (TextView) v.findViewById(R.id.month_grpby);
dfgnew = (LinearLayout) v.findViewById(R.id.dfgnew);
product_header2 = (LinearLayout) v.findViewById(R.id.product_header2);
}
}
}
I have a fragment in my Activity with the below structure:
<android.support.v7.widget.RecyclerView android:id="#+id/cafeRecyclerView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
it has only a RecyclerView. and it has an Adapter with the below code:
public class InfinityFragmentRecyclerAdapter extends RecyclerView.Adapter implements HasDatabase
{
protected JsonDatabase jsonDatabase = new JsonDatabase();
protected Context mContext;
protected int arrangeMode;
public InfinityFragmentRecyclerAdapter(Context context, int viewMode)
{
mContext = context;
arrangeMode = viewMode;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View view;
if (arrangeMode == SupportsGridAndListArrangement.GRID_VIEW)
{
view = LayoutInflater.from(viewGroup.getContext()).inflate
(R.layout.grid_advertisement_layout, null);
}
else
{
view = LayoutInflater.from(viewGroup.getContext()).inflate
(R.layout.list_advertisement_layout, null);
}
return new ItemHolder(view, mContext, arrangeMode);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i)
{
AdItemPassiveDataSet adItemPassiveDataSet = (AdItemPassiveDataSet) jsonDatabase.getDataSetAt(i);
Picasso.with(mContext).load(adItemPassiveDataSet.getItemThumbnailAddress()).into
(((ItemHolder) viewHolder).imageView);
((ItemHolder) viewHolder).adID = adItemPassiveDataSet.getItemID();
((ItemHolder) viewHolder).userID = adItemPassiveDataSet.getUserID();
((ItemHolder) viewHolder).userRole = adItemPassiveDataSet.getUserRole();
((ItemHolder) viewHolder).price.setText(adItemPassiveDataSet.getItemPrice(), false);
((ItemHolder) viewHolder).title.setText(adItemPassiveDataSet.getItemTitle(), false);
((ItemHolder) viewHolder).state.setText(adItemPassiveDataSet.getItemState(), false);
((ItemHolder) viewHolder).date.setText(adItemPassiveDataSet.getItemTime(), false);
if (arrangeMode == SupportsGridAndListArrangement.LIST_VIEW)
{
((ItemHolder) viewHolder).description.setText(adItemPassiveDataSet.getItemDescription());
StaggeredGridLayoutManager.LayoutParams layoutParams =
new StaggeredGridLayoutManager.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
viewHolder.itemView.setLayoutParams(layoutParams);
}
}
#Override
public int getItemCount()
{
if (jsonDatabase != null)
{
return jsonDatabase.getCount();
}
else
{
return 0;
}
}
#Override
public JsonDatabase getDatabase()
{
return jsonDatabase;
}
public void append(Object newJsonDatabase)
{
int currentCount = 0;
if (jsonDatabase != null)
{
currentCount = jsonDatabase.getCount();
}
int newCount = ((JsonDatabase) newJsonDatabase).getCount();
jsonDatabase.appendAtEnd((JsonDatabase) newJsonDatabase);
for (int i = currentCount; i < (currentCount + newCount); i++)
{
notifyItemInserted(i);
}
}
}
I also setup my fragment at this way:
recyclerView = (RecyclerView) findViewById(R.id.cafeRecyclerView);
recyclerViewAdapter = new InfinityFragmentRecyclerAdapter(this, SupportsGridAndListArrangement.GRID_VIEW);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
and each time I receive new data from server, I add them to RecyclerView in CardViews at this way:
recyclerViewAdapter.append(newJsonDatabase);
every thing is fine! I can download data, add them to recycler view and so on but the problem is that the recycler view doesnt scroll fluently. when the top or bottom of my cardviews in recycler view reach to the top of recycler view, it somehow sticks and jumps some pixels! I'm really confused. any idea please? any help will be appreciated.
try to use notifyItemRangeInserted() instead of notifyItemInserted()
if I understand correctly your code should be like this
notifyItemInserted(currentCount, currentCount + newCount);
I have a recyclerView with 2 ViewTypes: Images and 1 button. When I click that button I'm able to add one more image each time. I want that when I have 5 images, the button to disappear, without using setView(Gone). Here is my adapter, and I'm trying to remove the button in onBindViewHolder:
public class SelectPhotoAdapter extends
RecyclerView.Adapter<SelectPhotoHolder> {// Recyclerview will extend to
// recyclerview adapter
private ArrayList<Data_Model> arrayList;
private Context context;
private boolean hasLoadButton = true;
private final int IMAGES = 0;
private final int LOAD_MORE = 1;
public SelectPhotoAdapter (Context context,
ArrayList<Data_Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
public boolean itHasLoadButton() {
return hasLoadButton;
}
public void setHasLoadButton(boolean hasLoadButton) {
this.hasLoadButton = hasLoadButton;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if (hasLoadButton) {
return arrayList==null? 1 :arrayList.size() + 1;
} else {
return arrayList==null? 0 :arrayList.size();
}
}
#Override
public int getItemViewType(int position) {
if (position < getItemCount()-1) {
return IMAGES;
} else {
return LOAD_MORE;
}
}
#Override
public void onBindViewHolder(SelectPhotoHolder holder, int position) {
SelectPhotoHolder mainHolder = holder;// holder
if(position >= getItemCount() -1) {
mainHolder.addPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
arrayList.add(new Data_Model(SelectPhotoDialogFragment.IMAGES[0]));
SelectPhotoDialogFragment.adapter.notifyItemInserted(arrayList.size());
SelectPhotoDialogFragment.mRecyclerView.scrollToPosition(arrayList.size());
Log.d("askj","Sizee: "+arrayList.size());
if(arrayList.size()>5&&itHasLoadButton()){
setHasLoadButton(false);
SelectPhotoDialogFragment.adapter.notifyItemRemoved(arrayList.size() + 1);
SelectPhotoDialogFragment.adapter.notifyItemRangeChanged(arrayList.size() + 1, getItemCount());
Log.e("askj", "calledLoad");
}
}
});
} else {
final Data_Model model = arrayList.get(position);
Bitmap image = BitmapFactory.decodeResource(context.getResources(),
model.getImagePath());// This will convert drawbale image into
mainHolder.imageview.setImageBitmap(image);
}
}
#Override
public SelectPhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == IMAGES) {
return new SelectPhotoHolder((LayoutInflater.from(parent.getContext()).inflate(R.layout.selectphotolist, parent, false)),IMAGES);
} else if (viewType == LOAD_MORE) {
return new SelectPhotoHolder((LayoutInflater.from(parent.getContext()).inflate(R.layout.addphoto, parent, false)),LOAD_MORE);
} else {
return null;
}
}
}
The method is called(I can see in the console 'calledLoad'), but the button is still there. I thought that by calling setHasLoadButton(false) the button will disappear, but it's not happening.
Let me know if I have to add more code.
You can change condition in getItemViewType from position < getItemCount()-1 to arrayList!=null && position < arrayList.size().
Better also to move management of OnClickListener interface directly into ViewHolder.