How to set layout visiblity inside recycleview adapter, my adapter code is - android

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

Related

How to efficiently loading native ads on demand with the recyclerview adapter?

What i am doing is, that i have a recyclerView which has it's adapter and from within adapter i am loading the nativeAds. But due to loading the ads within the recyclerView instead of preloading the ads my recyclerView is not scrolling smoothly.
And also i tried to load the native ad on different thread but that also was't helpful.
Any ideas how to load the native ad without sacrificing the performance??
public class GetInspiredAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static int VIEW_TYPE_ADS = 0;
public static int VIEW_TYPE_NOTADS = 1;
// this shows that the ad is to be added after this many items.
public static int ADS_AFTER_HOW_MANY_ITEMS = 3;
private boolean isNetworkAvailable = false;
private Context context;
private ArrayList<Object> list;
private GetInspiredListener listener;
public GetInspiredAdapter(Context context, ArrayList<Object> list, GetInspiredListener listener) {
this.context = context;
this.list = list;
this.listener = listener;
}
private void addNativeToList() {
int i = ADS_AFTER_HOW_MANY_ITEMS;
while (i < list.size()) {
list.add(i, new UnifiedNativeAdView(context));
i += ADS_AFTER_HOW_MANY_ITEMS + 1;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
if (viewType == VIEW_TYPE_ADS) {
View unifiedNativeLayoutView = LayoutInflater.from(context).inflate(R.layout.ad_unified, viewGroup, false);
unifiedNativeLayoutView.setTag(new Integer(GetInspiredAdapter.VIEW_TYPE_ADS));
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
} else {
View itemView = LayoutInflater.from(context).inflate(R.layout.image_item, viewGroup, false);
itemView.setTag(new Integer(GetInspiredAdapter.VIEW_TYPE_NOTADS));
return new GetInspiredViewHolder(itemView);
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
if (viewType == VIEW_TYPE_ADS) {
if (!isNetworkAvailable) {
list.remove(position);
notifyDataSetChanged();
return;
}
AdLoader.Builder builder = new AdLoader.Builder(context, Constants.INSPIRED_MOB)
.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
populateNativeAdView(unifiedNativeAd, (UnifiedNativeAdViewHolder) holder);
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
}
});
builder.build().loadAd(new AdRequest.Builder().build());
} else if (viewType == VIEW_TYPE_NOTADS) {
LoadImage((InspiredObject) list.get(getItemIndex(position)), (GetInspiredViewHolder) holder);
}
}
private void LoadImage(InspiredObject obj, GetInspiredViewHolder viewHolder) {
//Url link to images
String url = "http://aim-itech.com/mandala/image/";
String string = url + obj.low;
Glide.with(context).load(string).override(Constants.SAMPLE_SIZE_MEDIUM).into(viewHolder.imageView);
Log.e("TAG", string);
}
private void populateNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdViewHolder holder) {
if (nativeAd == null) {
holder.getAdView().setVisibility(View.INVISIBLE);
holder.textLoading.setVisibility(View.VISIBLE);
return;
}
holder.textLoading.setVisibility(View.GONE);
UnifiedNativeAdView adView = holder.getAdView();
adView.setVisibility(View.VISIBLE);
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
NativeAd.Image icon = nativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeAd);
}
public int getItemIndex(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = list.get(getItemIndex(position));
if (recyclerViewItem instanceof UnifiedNativeAd) {
return VIEW_TYPE_ADS;
} else if (recyclerViewItem instanceof UnifiedNativeAdView) {
return VIEW_TYPE_ADS;
}
return VIEW_TYPE_NOTADS;
}
public boolean isNetworkAvailable() {
return isNetworkAvailable;
}
public void setNetworkAvailable(boolean networkAvailable) {
isNetworkAvailable = networkAvailable;
if (isNetworkAvailable) {
addNativeToList();
}
}
#Override
public int getItemCount() {
return list.size();
}
public class GetInspiredViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public GetInspiredViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageProf);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InspiredObject inspiredObject = (InspiredObject) list.get(getAdapterPosition());
Intent i = new Intent(context, InspiredActivity.class);
i.putExtra("image", inspiredObject.high);
listener.onClick(i);
}
});
}
}
public class UnifiedNativeAdViewHolder extends RecyclerView.ViewHolder {
private UnifiedNativeAdView adView;
private TextView textLoading;
private CardView adContainer;
public UnifiedNativeAdView getAdView() {
return adView;
}
UnifiedNativeAdViewHolder(View view) {
super(view);
textLoading = view.findViewById(R.id.native_loading_text);
adView = view.findViewById(R.id.native_ad_view);
adContainer = view.findViewById(R.id.ad_unified_conatiner);
// The MediaView will display a video asset if one is present in the ad, and the
// first image asset otherwise.
adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));
// Register the view used for each individual asset.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setBodyView(adView.findViewById(R.id.ad_body));
adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
adView.setIconView(adView.findViewById(R.id.ad_icon));
adView.setPriceView(adView.findViewById(R.id.ad_price));
adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
adView.setStoreView(adView.findViewById(R.id.ad_store));
adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));
}
}
}
surprised there is no answer here.
The approach I would use outside of the recyclerview adapter:
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS_TO_LOAD(Max 5 according to docs);
instead usual adLoader.loadAd
and then
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
}
});
where
private List<UnifiedNativeAd> nativeAds = new ArrayList<>();
which you pass to your recyclerview adapter and mix in your other items.
This will need some memory handling with destroy called before you request another list etc. but the idea is to preload a list of ads instead of loading them while scrolling

Nested RecyclerView onClick not triggered

I have two nested RecyclerViews - basically a list of horizontal RecyclerViews and I am struggling to make the items in the horizontal RecyclerView clickable.
This is the main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/overview_list"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<components.emptyView.EmptyView
android:id="#+id/empty_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"/>
</LinearLayout>
Then RecyclerView has the following item layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView android:id="#+id/tables"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:clipToPadding="false"
android:paddingEnd="18dp"
android:paddingStart="18dp"/>
And I'm trying to get the onclick setup in the adapter for the inner RecyclerView as follows:
#Override
public void onBindViewHolder(#NonNull LeagueTableViewHolder holder, int position) {
Pair<Long, String> table = tables.get(position);
holder.bindTable(table.first, table.second);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// click event here
}
});
}
I've tried making the ViewHolder's itemview as clickable programatically and in XML and it doesn't seem to make a difference. Same for the inner RecyclerView.
Any idea what I'm doing wrong?
Edit: Added parent RecyclerView adapter
public class OverviewListAdapter extends RecyclerView.Adapter<BaseViewHolder> {
public final static int TEAM_PICTURE = 0;
public final static int FIXTURES = 1;
public final static int LEAGUE_TABLES = 2;
public final static int LATEST_NEWS = 3;
public final static int LATEST_EVENTS = 4;
private final RecyclerView.RecycledViewPool viewPool;
private List<BaseOverviewItemVM> viewModels = new ArrayList<>();
private int tint;
private OverviewLatestNewsVM newsVM;
private OverviewLatestEventsVM eventsVM;
private OverviewTablesVM tablesVM;
private OverviewFixturesVM fixturesVM;
private OverviewTeamPicVM teamPicVM;
OverviewListAdapter(int tint) {
this.tint = tint;
viewPool = new RecyclerView.RecycledViewPool();
}
void addViewModel(OverviewLatestNewsVM viewModel){
if(newsVM == null){
newsVM = viewModel;
viewModels.add(newsVM);
sort();
int viewModelIndex = viewModels.indexOf(newsVM);
notifyItemInsertedIfValid(viewModelIndex);
} else {
int currentNewsIndex = viewModels.indexOf(newsVM);
newsVM = viewModel;
if(currentNewsIndex >= 0) {
this.viewModels.set(currentNewsIndex, newsVM);
}
notifyItemChangedIfValid(currentNewsIndex);
}
}
void addViewModel(OverviewLatestEventsVM viewModel){
if(eventsVM == null){
eventsVM = viewModel;
viewModels.add(eventsVM);
sort();
int viewModelIndex = viewModels.indexOf(eventsVM);
notifyItemChangedIfValid(viewModelIndex);
} else {
int currentIndex = viewModels.indexOf(eventsVM);
eventsVM = viewModel;
if(currentIndex >= 0) {
this.viewModels.set(currentIndex, eventsVM);
}
notifyItemChangedIfValid(currentIndex);
}
}
void addViewModel(OverviewFixturesVM viewModel){
if(fixturesVM == null){
fixturesVM = viewModel;
viewModels.add(fixturesVM);
sort();
int viewModelIndex = viewModels.indexOf(fixturesVM);
notifyItemChangedIfValid(viewModelIndex);
} else {
int currentIndex = viewModels.indexOf(fixturesVM);
fixturesVM = viewModel;
if(currentIndex >= 0) {
this.viewModels.set(currentIndex, fixturesVM);
}
notifyItemChangedIfValid(currentIndex);
}
}
void addViewModel(OverviewTablesVM viewModel){
if(tablesVM == null){
tablesVM = viewModel;
viewModels.add(tablesVM);
sort();
int viewModelIndex = viewModels.indexOf(tablesVM);
notifyItemChangedIfValid(viewModelIndex);
} else {
int currentIndex = viewModels.indexOf(tablesVM);
tablesVM = viewModel;
if(currentIndex >= 0) {
this.viewModels.set(currentIndex, tablesVM);
}
notifyItemChangedIfValid(currentIndex);
}
}
void addViewModel(OverviewTeamPicVM viewModel){
if(teamPicVM == null){
teamPicVM = viewModel;
viewModels.add(teamPicVM);
sort();
int viewModelIndex = viewModels.indexOf(teamPicVM);
notifyItemChangedIfValid(viewModelIndex);
} else {
int currentIndex = viewModels.indexOf(teamPicVM);
teamPicVM = viewModel;
if(currentIndex >= 0) {
this.viewModels.set(currentIndex, teamPicVM);
}
notifyItemChangedIfValid(currentIndex);
}
}
private void sort(){
// sort by the item type defined at the top of this class
Collections.sort(viewModels, (o1, o2) -> {
if(o1.getType() > o2.getType()){
return 1;
} else if(o1.getType() < o2.getType()){
return -1;
}
return 0;
});
}
private void notifyItemInsertedIfValid(int index){
if(index >= 0 && index < getItemCount()){
notifyItemInserted(index);
} else {
notifyDataSetChanged();
}
}
private void notifyItemChangedIfValid(int index){
if(index >= 0 && index < getItemCount()){
notifyItemChanged(index);
} else {
notifyDataSetChanged();
}
}
#NonNull
#Override
public BaseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType){
case FIXTURES:
View fixturesView = inflater.inflate(R.layout.row_overview_fixtures, parent, false);
OverviewFixturesVH fixturesHolder = new OverviewFixturesVH(fixturesView);
fixturesHolder.fixturesOverview.setRecycledViewPool(viewPool);
return fixturesHolder;
case LEAGUE_TABLES:
View tablesView = inflater.inflate(R.layout.row_overview_league_tables, parent, false);
OverviewTablesVH tablesHolder = new OverviewTablesVH(tablesView);
tablesHolder.tablesList.setRecycledViewPool(viewPool);
return tablesHolder;
case LATEST_EVENTS:
View upcomingEvents = inflater.inflate(R.layout.row_latest_list_view, parent, false);
return new OverviewLatestEventsVH(upcomingEvents, tint);
case TEAM_PICTURE:
View teamPicView = inflater.inflate(R.layout.row_overview_team_pic, parent, false);
return new OverviewTeamPicVH(teamPicView);
default:
View latestNewsView = inflater.inflate(R.layout.row_latest_list_view, parent, false);
return new OverviewLatestNewsVH(latestNewsView, tint);
}
}
#Override
public void onBindViewHolder(#NonNull BaseViewHolder holder, int position) {
if(holder instanceof OverviewFixturesVH) {
Optional<BaseOverviewItemVM> fixturesVM = getViewModelOfType(FIXTURES);
fixturesVM.ifPresent(viewModel -> ((OverviewFixturesVH) holder).setFixtures(((OverviewFixturesVM)viewModel).getFixtures()));
} else if (holder instanceof OverviewTablesVH) {
Optional<BaseOverviewItemVM> tablesVM = getViewModelOfType(LEAGUE_TABLES);
tablesVM.ifPresent(vm -> ((OverviewTablesVH) holder).setTableIds(((OverviewTablesVM) vm).getTableIds()));
} else if (holder instanceof OverviewLatestEventsVH){
Optional<BaseOverviewItemVM> eventsVM = getViewModelOfType(LATEST_EVENTS);
eventsVM.ifPresent(vm -> ((OverviewLatestEventsVH) holder).setEvents(((OverviewLatestEventsVM) vm).getEvents()));
} else if (holder instanceof OverviewLatestNewsVH){
Optional<BaseOverviewItemVM> newsVM = getViewModelOfType(LATEST_NEWS);
newsVM.ifPresent(vm -> ((OverviewLatestNewsVH) holder).setNews(((OverviewLatestNewsVM) vm).getNews()));
} else if (holder instanceof OverviewTeamPicVH){
Optional<BaseOverviewItemVM> teamPicVM = getViewModelOfType(TEAM_PICTURE);
teamPicVM.ifPresent(vm -> ((OverviewTeamPicVH) holder).setPictureUrl(((OverviewTeamPicVM) vm).getTeamPicUrl()));
}
}
#Override
public int getItemViewType(int position) {
return viewModels.get(position).getType();
}
#Override
public int getItemCount() {
return viewModels.size();
}
private Optional<BaseOverviewItemVM> getViewModelOfType(int type){
if(viewModels != null ) {
for (BaseOverviewItemVM viewModel : viewModels) {
if(viewModel.getType() == type){
return Optional.of(viewModel);
}
}
}
return Optional.empty();
}
}
I think you will be able to handle it creating a listener and handle the call with it:
public interface clickListenerItem {
void onItemClick(Item element);
}
add this interface in your adapter and in your main.
Adding this function to your *nameclass*ViewHolder extends RecyclerView.ViewHolder :
public void bind(final ItemName item, final clickListenerItem listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
then add to your Adapter variables: private final clickListenerItem clickItem;
in your constructor: this.clickItem = clickItem;
and in onBindViewHolder of your adapter call:
public void onBindViewHolder(final #NonNull ItemViewHolder holder, int position) {
holder.bind(list.get(position), clickItem);
}
now when initiliazing your adapter in the main you just add your listener adding it with a call like this:
adapter = new ItemAdapter(this, list, (new ItemAdapter.clickListenerItem(){
#Override public void onItemClick(Item thisItem) {
Toast.makeText(getApplicationContext(), "Loading Item...", Toast.LENGTH_LONG).show();
Intent viewElem = new Intent(getApplicationContext(), ViewItem.class);
startActivityForResult(viewElem ,codeForResult);
}
}));
I hope this will help you, obviusly you can change the last part for not calling a new activity but changing it with what you want to see or do with your item.

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

change the layout of views in a recycler view

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

Add ProgressBar when recyclerView hit scroll

I have to add Pagination in recyclerView. But I am stuck in adding a progressbar when recyclerView scroll.
I have been trying for a day but unfortunately not got a valid solution to add a progress bar at run time while recyclerView scrolling.I have three ViewHolder.
RecyclerView Scroll Listener
rvRewardItems.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = wrapperLinearLayout.getItemCount();
int firstVisibleItem = wrapperLinearLayout.findFirstVisibleItemPosition();
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !isLoadingMore) {
if (!mStopLoadingData) {
try {
isLoadingMore = true;
// Add item for progress ba
new Handler().post(new Runnable() {
#Override
public void run() {
adapter.addProgressView();
}
});
loadReviews(false, false);
}catch (IllegalStateException e){
e.printStackTrace();
}
}
}
}
});
RewardFinalAdapter.class
public class RewardFinalAdapter extends RecyclerView.Adapter<MainViewHolder>
{
private Context context;
private ArrayList<RewardItemBO> rewardArray;
private OnItemClickListener mItemClickListener;
public static final int VIEW_TYPE_PROGRESS = 0;
public static final int VIEW_TYPE_ITEM = 1;
public static final int VIEW_TYPE_HEADER = 2;
public RewardFinalAdapter(Context context, ArrayList<RewardItemBO> mainItems) {
this.context = context;
rewardArray = getFilterRewards(mainItems);
}
public void resetArray(ArrayList<RewardItemBO> latestArray)
{
rewardArray = getFilterRewards(latestArray);
}
public void setArrayItems(ArrayList<RewardItemBO> latestArray) {
rewardArray = latestArray;
}
#Override
public int getItemViewType(int position) {
if(rewardArray.get(position).isHeader())
return VIEW_TYPE_HEADER;
else if(rewardArray.get(position).isShowProgress())
return VIEW_TYPE_PROGRESS;
else
return VIEW_TYPE_ITEM;
}
#Override
public int getItemCount() {
return rewardArray.size();
}
public RewardItemBO getItem(int position) {
return rewardArray.get(position);
}
public void addItems( ArrayList<RewardItemBO> overallItem){
rewardArray = getFilterRewards(overallItem);
// notifyItemInserted(items.size() - 1);
this.notifyDataSetChanged();
}
// Create new views (invoked by the layout manager)
#Override
public MainViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType){
case VIEW_TYPE_HEADER:
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.order_list_header, viewGroup, false);
return new RewardListViewHolderHeader(itemView);
case VIEW_TYPE_ITEM:
View view = LayoutInflater.from(context).inflate(R.layout.item_rewards, viewGroup, false);
return new RewardViewHolder(view);
case VIEW_TYPE_PROGRESS:
Log.v("view_type_progress","I am in VIEW_TYPE_PROGRESS");
View progressView = LayoutInflater.from(context).inflate(R.layout.progress_loader, viewGroup, false);
return new ProgressViewHolder(progressView);
}
return null;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MainViewHolder viewHolder, int position) {
RewardItemBO rewardItemBO= rewardArray.get(position);
if(viewHolder instanceof RewardViewHolder)
{
RewardViewHolder rewardViewHolder=(RewardViewHolder) viewHolder;
rewardViewHolder.tvRewardTitle.setText(rewardArray.get(position).getRewardTitle());
rewardViewHolder.tvRewardDescription.setText(rewardArray.get(position).getRewardMessage());
String formatedDate = DateTimeOp.oneFormatToAnother(rewardArray.get(position).getRewardExpiryDate(), Constants.dateFormat18, Constants.dateFormat6);
rewardViewHolder.tvRewardExpiry.setText("Expires " + formatedDate);
if(rewardArray.get(position).getRewardShowRedeem().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Redeemed");
}
else if(rewardArray.get(position).getRewardExpired().equals("1"))
{
rewardViewHolder.btnGrey.setVisibility(View.VISIBLE);
rewardViewHolder.btnGrey.setText("Expired");
}
else
{
rewardViewHolder.btnOrange.setVisibility(View.VISIBLE);
rewardViewHolder.btnOrange.setText("Get Code");
}
}
else if(viewHolder instanceof RewardListViewHolderHeader)
{
RewardListViewHolderHeader holder = (RewardListViewHolderHeader ) viewHolder;
holder.tvHeader.setText(rewardItemBO.getHeaderTitle());
}
else if(viewHolder instanceof ProgressViewHolder)
{
ProgressViewHolder progressViewHolder = (ProgressViewHolder) viewHolder;
progressViewHolder.progressBar.setIndeterminate(true);
}
}
public void addOnTop(ArrayList<RewardItemBO> topItemList) {
Collections.reverse(topItemList);
rewardArray.addAll(0, topItemList);
notifyItemRangeInserted(0, topItemList.size());
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
#Override
public long getItemId(int position) {
return position;
}
public ArrayList<RewardItemBO> getFilterRewards(ArrayList<RewardItemBO> mainItems){
ArrayList<RewardItemBO> currentRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> pastRewardList = new ArrayList<RewardItemBO>();
ArrayList<RewardItemBO> dummyArray = new ArrayList<>();
for (RewardItemBO rewardItemBO : mainItems) {
try {
//because reward item with progress have everything null in it.
if(rewardItemBO.getRewardExpired()!=null && !rewardItemBO.isShowProgress())
{
int isExpired = Integer.parseInt(rewardItemBO.getRewardExpired());
if(isExpired==1)
pastRewardList.add(rewardItemBO);
else
currentRewardList.add(rewardItemBO);
}
}catch (NumberFormatException e){
e.printStackTrace();
}
}
if(currentRewardList.size()>0){
currentRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Current)));
dummyArray.addAll(currentRewardList);
}
if(pastRewardList.size()>0){
pastRewardList.add(0, new RewardItemBO(context.getResources().getString(R.string.Past)));
dummyArray.addAll(pastRewardList);
}
return dummyArray;
}
public void addProgressView()
{
rewardArray.add(new RewardItemBO(true));
//notifyItemChanged(rewardArray.size());
notifyDataSetChanged();
}
public void removeProgressView(){
int position = rewardArray.size() -1;
rewardArray.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, rewardArray.size());
}
public static class RewardListViewHolderHeader extends MainViewHolder {
protected TextView tvHeader;
public RewardListViewHolderHeader (View v) {
super(v);
tvHeader = (TextView) v.findViewById(R.id.header_text);
}
}
public class RewardViewHolder extends MainViewHolder implements View.OnClickListener{
public TextView tvRewardTitle;
public TextView tvRewardDescription;
public TextView tvRewardExpiry;
public Button btnOrange,btnGrey;
public RewardViewHolder(View v) {
super(v);
tvRewardTitle = (TextView) itemView.findViewById(R.id.tv_reward_title);
tvRewardDescription = (TextView) itemView.findViewById(R.id.tv_reward_description);
tvRewardExpiry = (TextView) itemView.findViewById(R.id.tv_reward_expiry_date);
btnOrange = (Button) itemView.findViewById(R.id.btn_item_reward_orange);
btnGrey = (Button) itemView.findViewById(R.id.btn_item_reward_grey);
btnOrange.setOnClickListener(this);
btnGrey.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Toast.makeText(context, tvName.getText().toString(), Toast.LENGTH_SHORT).show();
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v,getAdapterPosition());
}
}
}
}

Categories

Resources