I have found this library and I want to implement it in my app:
cardslider-android--Github
In my case I have events and I want to query their name, time, description and picture and, each time I select a card, they will change dynamically in the same fragment.
This is the event adapter:
public class EventsAdapter extends FirestoreRecyclerAdapter < EventsModel, EventsAdapter.EventsViewHolder > {
public EventsAdapter(FirestoreRecyclerOptions < EventsModel > options) {
super(options);
}
DocumentSnapshot documentSnapshot;
#Override
protected void onBindViewHolder(#NonNull EventsViewHolder holder, int position, #NonNull EventsModel eventsModel) {
holder.nameSwitcher.setText(eventsModel.getEvent_name());
holder.timeSwitcher.setText(eventsModel.getEvent_date());
holder.descriptionsSwitcher.setText(eventsModel.getEvent_desc());
GlideApp.with(holder.eventpic.getContext())
.load(eventsModel.getEvent_pic())
.into(holder.eventpic);
String documentID = getSnapshots().getSnapshot(position).getId();
eventsModel.setDocid(documentID);
}
#NonNull
#Override
public EventsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_past_event, parent, false);
return new EventsViewHolder(view);
}
public class EventsViewHolder extends RecyclerView.ViewHolder {
private TextView eventname;
private Button morebtn;
private ImageView eventpic;
private TextSwitcher nameSwitcher;
private TextSwitcher timeSwitcher;
private TextSwitcher descriptionsSwitcher;
public EventsViewHolder(#NonNull View itemView) {
super(itemView);
nameSwitcher = itemView.findViewById(R.id.ts_name);
timeSwitcher = itemView.findViewById(R.id.ts_time);
descriptionsSwitcher = itemView.findViewById(R.id.ts_description);
}
}
}
This is the Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root_past_event_view = inflater.inflate(R.layout.fragment_past_event, container, false);
mFirestoreList = (RecyclerView) root_past_event_view.findViewById(R.id.xrecyclerview_events);
firebaseFirestore = FirebaseFirestore.getInstance();
Query query = firebaseFirestore.collection("events");
FirestoreRecyclerOptions < EventsModel > options = new FirestoreRecyclerOptions
.Builder < EventsModel > ()
.setQuery(query, EventsModel.class)
.build();
adapter = new EventsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new CardSliderLayoutManager(getContext()));
mFirestoreList.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
onActiveCardChange();
}
}
});
mFirestoreList.setLayoutManager(new CardSliderLayoutManager(getContext()));
new CardSnapHelper().attachToRecyclerView(mFirestoreList);
mFirestoreList.setAdapter(adapter);
nameSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_name);
nameSwitcher.setFactory(new TextViewFactory(R.style.nameTextView, false));
timeSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_time);
timeSwitcher.setFactory(new TextViewFactory(R.style.timeTextView, false));
descriptionsSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_description);
descriptionsSwitcher.setInAnimation(getContext(), android.R.anim.fade_in);
descriptionsSwitcher.setOutAnimation(getContext(), android.R.anim.fade_out);
descriptionsSwitcher.setFactory(new TextViewFactory(R.style.DescriptionTextView, false));
return root_past_event_view;
}
private void initRecyclerView() {
}
private void onActiveCardChange() {
final int pos = layoutManger.getActiveCardPosition();
if (pos == RecyclerView.NO_POSITION || pos == currentPosition) {
return;
}
onActiveCardChange(pos);
}
private void onActiveCardChange(int pos) {
int animH[] = new int[] {
R.anim.slide_in_right, R.anim.slide_out_left
};
int animV[] = new int[] {
R.anim.slide_in_top, R.anim.slide_out_bottom
};
final boolean left2right = pos < currentPosition;
if (left2right) {
animH[0] = R.anim.slide_in_left;
animH[1] = R.anim.slide_out_right;
animV[0] = R.anim.slide_in_bottom;
animV[1] = R.anim.slide_out_top;
}
//setCountryText(countries[pos % countries.length], left2right);
nameSwitcher.setInAnimation(getContext(), animV[0]);
nameSwitcher.setOutAnimation(getContext(), animV[1]);
timeSwitcher.setInAnimation(getContext(), animV[0]);
timeSwitcher.setOutAnimation(getContext(), animV[1]);
currentPosition = pos;
}
private class TextViewFactory implements ViewSwitcher.ViewFactory {
#StyleRes
final int styleId;
final boolean center;
TextViewFactory(#StyleRes int styleId, boolean center) {
this.styleId = styleId;
this.center = center;
}
#SuppressWarnings("deprecation")
#Override
public View makeView() {
final TextView textView = new TextView(getContext());
if (center) {
textView.setGravity(Gravity.CENTER);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
textView.setTextAppearance(getContext(), styleId);
} else {
textView.setTextAppearance(styleId);
}
return textView;
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I changed the LayoutInflater to include the whole fragment and I do not get a single card but the following error:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Related
So, basically what I am trying to do is to show a bunch of Post type objects on my Android app's feed (HomeFragment). The posts are being successfully retrieved from Firestore (I did check the debugger) but somehow, not all of them get loaded in the recyclerView. The itemViewHolder is only loaded with how I defined it as an XML, fields filled with lore Ipsum.
This would be my code:
HomeFragment:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private boolean isLoading = false;
private ArrayList<String> rowsArrayList = new ArrayList<>();
public static ArrayList<Post> appliedToList = new ArrayList<>();
private User currentUser = new User();
private View root;
private TextView userState;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
setState();
appliedToPostsRetrieverFromHomePage(getContext());
checkForPostFragment();
recyclerView = root.findViewById(R.id.recyclerView);
initAdapter();
initScrollListener();
return root;
}
private void initAdapter() {
recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), 2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(recyclerViewAdapter);
}
private void initScrollListener() {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (!isLoading) {
if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) {
//bottom of list!
loadMore();
isLoading = true;
}
}
}
});
}
private void loadMore() {
rowsArrayList.add(null);
recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
rowsArrayList.remove(rowsArrayList.size() - 1);
int scrollPosition = rowsArrayList.size();
recyclerViewAdapter.notifyItemRemoved(scrollPosition);
int currentSize = scrollPosition;
int nextLimit = currentSize + 10;
while (currentSize - 1 < nextLimit) {
rowsArrayList.add("Item " + currentSize);
currentSize++;
}
recyclerViewAdapter.notifyDataSetChanged();
isLoading = false;
}
}, 2000);
}
#Override
public void onAttachFragment(#NonNull Fragment fragment) {
super.onAttachFragment(fragment);
}
RecyclerViewAdapter:
All view types represent kind of the same layout, the only difference between them is what is wrote on a certain button. Remember, some of the posts are successfully loaded!
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_APPLY = 0;
private final int VIEW_TYPE_MORE = 1;
private final int VIEW_TYPE_BEGIN = 2;
private final int VIEW_TYPE_PENDING = 3;
private final int VIEW_TYPE_END = 4;
private final int VIEW_TYPE_ON_GOING = 5;
private final int VIEW_TYPE_LOADING = 6;
private ArrayList<Post> list = new ArrayList();
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
private Context context;
private User currentUser;
private int recyclerType;
static ArrayList<User> applicantsList = new ArrayList<>();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
public RecyclerViewAdapter(Context context, int recyclerType) {
this.context = context;
this.recyclerType = recyclerType;
if (recyclerType == 0) {
myPostsRetriever(context);
} else if (recyclerType == 1) {
appliedToPostsRetriever(context);
} else if (recyclerType == 2) {
homePostsRetriever(context);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_APPLY) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_apply, parent, false);
return new ItemViewHolder(view);
} else if (viewType == VIEW_TYPE_MORE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_more, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_BEGIN) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_begin, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_PENDING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_pending, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_END) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_end, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_ON_GOING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_on_going, parent, false);
return new LoadingViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
return new LoadingViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
populateItemRows((ItemViewHolder) viewHolder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
showLoadingView((LoadingViewHolder) viewHolder, position);
}
}
#Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
#Override
public int getItemViewType(int position) {
if (list.get(position) != null) {
if (!list.get(position).getOwner().equals(userId) &&
!checkIfAlreadyAppliedToPost(position) &&
list.get(position).getMinNeededPersons() >= list.get(position).getApplicants()) {
return VIEW_TYPE_APPLY;
} else if (recyclerType == 1) {
return VIEW_TYPE_MORE;
} else if (list.get(position).getOwner().equals(userId) && timeCheck(list.get(position))) {
return VIEW_TYPE_BEGIN;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)
|| !list.get(position).getOwner().equals(userId) && checkIfAlreadyAppliedToPost(position) && !checkIfStarted(position)) {
return VIEW_TYPE_PENDING;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)) {
return VIEW_TYPE_END;
} else if (!list.get(position).getOwner().equals(userId) && checkIfStarted(position)){
return VIEW_TYPE_ON_GOING;
}else if (list.get(position).getOwner().equals(userId))
return VIEW_TYPE_MORE;
}
return VIEW_TYPE_LOADING;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView description;
TextView location;
TextView minNeededPersons;
TextView maxNeededPersons;
TextView reward;
TextView time;
CheckBox physical;
Button button;
ItemViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.postTitle);
description = itemView.findViewById(R.id.postDescription);
location = itemView.findViewById(R.id.postLocationText);
time = itemView.findViewById((R.id.postDateAndTime));
minNeededPersons = itemView.findViewById(R.id.people);
maxNeededPersons = itemView.findViewById(R.id.people);
reward = itemView.findViewById(R.id.reward);
physical = itemView.findViewById(R.id.checkBox2);
button = itemView.findViewById(R.id.applyButton);
}
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
private void showLoadingView(LoadingViewHolder viewHolder, int position) {
}
private void populateItemRows(ItemViewHolder viewHolder, int position) {
Post item = list.get(position);
viewHolder.title.setText(item.getTheTitle());
viewHolder.description.setText(item.getDescription());
viewHolder.location.setText(item.getLocation());
viewHolder.location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showLocation = new Intent(context, MapsActivity.class);
context.startActivity(showLocation);
}
});
viewHolder.minNeededPersons.setText(String.valueOf(item.getMinNeededPersons()));
viewHolder.maxNeededPersons.setText(String.valueOf(item.getMaxPersonsNeeded()));
viewHolder.reward.setText(String.valueOf(item.getReward()));
viewHolder.physical.setChecked(item.isPhysical());
Date timeAndDate = item.getTime().toDate();
viewHolder.time.setText(new SimpleDateFormat("HH:mm dd.MM.yyyy").format(timeAndDate));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if (viewHolder.button.getText().equals(context.getResources().getString(R.string.apply))) {
onApplyTapped(position);
viewHolder.button.setText(R.string.pending);
viewHolder.button.setBackgroundColor(Color.parseColor("#F2CF59"));
viewHolder.button.setClickable(false);
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.begin_job))) {
onBeginTapped(position);
viewHolder.button.setText(R.string.end_job);
viewHolder.button.setBackgroundColor(Color.parseColor("#F8CA9D"));
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.end_job))) {
onEndTapped(position);
viewHolder.button.setBackgroundColor(Color.parseColor("#FB8E7E"));
viewHolder.button.setClickable(false);
viewHolder.button.setText(R.string.finished);
}
}
});
viewHolder.itemView.findViewById(R.id.seePostButton).setOnClickListener(new View.OnClickListener()
{ not relevant }
private void homePostsRetriever(Context context) {
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collectionGroup("posts").limit(10).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) {
Post post = new Post();
post.setAvailability(documentSnapshot.getBoolean("available"));
post.setTitle(documentSnapshot.getString("title"));
post.setDescription(documentSnapshot.getString("description"));
post.setLocation(documentSnapshot.getString("location"));
post.setApplicants(documentSnapshot.getLong("applicants").intValue());
post.setOwner(documentSnapshot.getString("owner"));
post.setMinNeededPersons(documentSnapshot.getLong("minNrOfPeople").intValue());
post.setMaxPersonsNeeded(documentSnapshot.getLong("maxNrOfPeople").intValue());
post.setReward(Objects.requireNonNull(documentSnapshot.getLong("reward")).floatValue());
post.setPhysical(documentSnapshot.getBoolean("physicalExcertion"));
post.setTime(documentSnapshot.getTimestamp("time"));
post.setId(documentSnapshot.getId());
post.setStarted(documentSnapshot.getBoolean("started"));
list.add(post);
}
notifyDataSetChanged();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "No document found", Toast.LENGTH_SHORT).show();
}
});
}
I don't think you are calling bind methods correctly, try:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
ItemViewHolder holder = (ItemViewHolder)viewHolder;
holder.populateItemRows(holder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
LoadingViewHolder holder = (LoadingViewHolder)viewHolder;
holder.showLoadingView(holder , position);
}
}
Also this method:
private void populateItemRows(ItemViewHolder viewHolder, int position) {
.....
....
....
}
Is not found in your ItemViewHolder class
I've got a RecylerView that is displaying a list of data. I need to add dividers or spacers that I need to add two Dividers or spacers too that I can add text to as shown in the image below(with the text DEFAULT or OTHER).
*NOTE Headers are in the image below with the text "DEFAULT" and another that says "OTHER".
The CC's shown are drag and drop items but i don't want the "spaces or headers" marked as default and other to be moved.
I've started adding the divider as shown in the code below but I cannot figure out how to add text.
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
LinearLayoutManager mAdapterLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(mAdapterLayoutManager);
billingMethodRecyclerViewAdapter = new BillingMethodRecyclerViewAdapter(context, billingMethods, paymentService, ListPaymentMethods.this );
billingMethodRecyclerViewAdapter.setMasterpassService(masterpassService);
billingMethodRecyclerViewAdapter.setChoosePaymentMode(choosePaymentMode);
DividerItemDecoration itemDecor = new DividerItemDecoration(context, mAdapterLayoutManager.getOrientation());
recyclerView.addItemDecoration(itemDecor);
recyclerView.setAdapter(billingMethodRecyclerViewAdapter);
billingMethodRecyclerViewAdapter.clear();
if (!choosePaymentMode) {
setupSwipeListener(billingMethodRecyclerViewAdapter);
}
if (!BuildConfig.SHOW_AVAILABILITY_INRIX) {
parkmobileProAd.setVisibility(View.GONE);
}
if (getArguments() != null) {
isAddPaymentZoneDetails = getArguments().getBoolean(AddPaymentActivity.ADD_PAYMENT_FROM_ZONE_DETAIL);
}
}
and the xml for the recylcerview
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
EDIT
Adapter:
public class BillingMethodRecyclerViewAdapter extends RecyclerView.Adapter<BillingMethodHolder> {
private static final int PENDING_REMOVAL_TIMEOUT = 3000; // in milliseconds
private ArrayList<BillingMethod> billingMethods;
private Handler handler = new Handler(); // handler for running delayed runnables
private HashMap<BillingMethod, Runnable> pendingRunnables = new HashMap<>(); // map of items to pending runnables, so we can cancel a removal if need be
private BillingMethodHolder.BillingMethodListener billingMethodListener;
private PaymentService paymentService;
private MasterpassService masterpassService;
private boolean choosePaymentMode = false;
private Context mContext;
private int maxPaymentMethods = 6;
public BillingMethodRecyclerViewAdapter(Context context, ArrayList<BillingMethod> objects, PaymentService paymentService, BillingMethodHolder.BillingMethodListener billingMethodListener) {
this.billingMethods = objects;
this.billingMethodListener = billingMethodListener;
this.mContext = context.getApplicationContext();
this.paymentService = paymentService;
}
public int getMaxPaymentMethods() {
return maxPaymentMethods;
}
public void setMaxPaymentMethods(int maxPaymentMethods) {
this.maxPaymentMethods = maxPaymentMethods;
}
public void setMasterpassService(MasterpassService masterpassService) {
this.masterpassService = masterpassService;
}
public boolean onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(billingMethods, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(billingMethods, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
return true;
}
public List<BillingMethod> getBillingMethods() {
return billingMethods;
}
public void setChoosePaymentMode(boolean choosePaymentMode) {
this.choosePaymentMode = choosePaymentMode;
}
#NonNull
#Override
public BillingMethodHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_methods, parent, false);
return new BillingMethodHolder(v);
}
#Override
public void onBindViewHolder(#NonNull BillingMethodHolder holder, final int position) {
holder.bind(getBillingMethods().get(position), billingMethodListener, choosePaymentMode);
}
#Override
public int getItemCount() {
return billingMethods.size();
}
public void pendingRemoval(int position) {
final BillingMethod billingMethod = billingMethods.get(position);
billingMethod.setPendingDeletion(true);
this.notifyItemChanged(position); // redraw row in "undo" state
Runnable pendingRemovalRunnable = () -> {
deleteBillingMethod(position);
};
handler.postDelayed(pendingRemovalRunnable, PENDING_REMOVAL_TIMEOUT);
pendingRunnables.put(billingMethod, pendingRemovalRunnable);
}
public void savePaymentOrder() {
List<BillingMethod> newOrder = new ArrayList<>();
int order = 0;
for (BillingMethod method : billingMethods) {
if (order == 0) {
method.setPreferred(true);
LocalyticsUtil.getInstance(mContext).setPrimaryPaymentMethod(method);
} else {
method.setPreferred(false);
}
method.setSortOrder(order);
newOrder.add(method);
order++;
}
paymentService.setPaymentMethodsOrder(newOrder, new PaymentService.GenericListener() {
#Override
public void onSuccess() {
Log.d("TAG", "Saved");
}
#Override
public void onError(String errorMessage) {
Log.d("TAG", "Saved");
}
});
}
private void deleteBillingMethod(int position) {
BillingMethod method = billingMethods.get(position);
if (method.getBillingType() == BillingType.CREDIT_CARD) {
paymentService.deleteCreditCard(method.getCreditCard().getCardStatus(), new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.PREPAID) {
paymentService.deleteWallet(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.PAYPAL) {
paymentService.deletePaypal(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.CHASEPAY) {
paymentService.deleteChasepay(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.MASTERPASSV7) {
masterpassService.deleteMasterpassV7(String.valueOf(method.getBillingMethodId()), new MasterpassService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else {
notifyDataSetChanged();
}
}
public void clear() {
billingMethods.clear();
notifyDataSetChanged();
}
public void stopRemoval(BillingMethod billingMethod) {
Runnable pendingRemovalRunnable = pendingRunnables.get(billingMethod);
pendingRunnables.remove(billingMethod);
if (pendingRemovalRunnable != null) {
handler.removeCallbacks(pendingRemovalRunnable);
}
billingMethod.setPendingDeletion(false);
this.notifyItemChanged(billingMethods.indexOf(billingMethod));
}
}
I took a bit of time but I was able to do it.
This is the output
1) MainActivity.java
public class MainActivity extends AppCompatActivity implements OnStartDragListener{
RecyclerView recyclerView;
private ItemTouchHelper mItemTouchHelper;
private List<Item> itemList = new ArrayList<>();
private RecyclerViewAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mAdapter = new RecyclerViewAdapter(itemList, MainActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new SeparationDecorator());
recyclerView.setAdapter(mAdapter);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
prepareItemData();
}
private void prepareItemData() {
Item item = new Item("Apple Pay");
itemList.add(item);
item = new Item("1706-XXXX-XXXX-1112");
itemList.add(item);
item = new Item("Google pay");
itemList.add(item);
mAdapter.notifyDataSetChanged();
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
}
2) OnStartDragListener.java
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
3) SimpleItemTouchHelperCallback.java
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return false; // make this true to enable swipe to delete
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
4) ItemTouchHelperAdapter.java
public interface ItemTouchHelperAdapter {
void onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}
5) SeparationDecorator.java
public class SeparationDecorator extends RecyclerView.ItemDecoration {
private int textSize = 50;
private int groupSpacing = 100;
private Paint paint = new Paint();
{
paint.setTextSize(textSize);
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
if (position == 0) {
c.drawText("DEFAULT", view.getLeft(),
view.getTop() - groupSpacing / 2 + textSize / 3, paint);
} else if(position == 1) {
c.drawText("OTHER", view.getLeft(),
view.getTop() - groupSpacing / 2 + textSize / 3, paint);
}
}
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0 || parent.getChildAdapterPosition(view) == 1) {
outRect.set(0, groupSpacing, 0, 0);
}
}
}
6) RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements ItemTouchHelperAdapter{
private List<Item> itemList;
private Context context;
#Override
public void onItemMove(int fromPosition, int toPosition) {
Item prev = itemList.remove(fromPosition);
itemList.add(toPosition > fromPosition ? toPosition - 1 : toPosition, prev);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onItemDismiss(int position) {
itemList.remove(position);
notifyItemRemoved(position);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public RecyclerViewAdapter(List<Item> itemList, Context context) {
this.itemList = itemList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Item movie = itemList.get(position);
holder.title.setText(movie.getTitle());
}
#Override
public int getItemCount() {
return itemList.size();
}
}
7) Item.java
public class Item {
private String title;
public Item(String title) {
this.title = title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
This is it. This was able to solve your problem.
I am not able to explain you the complete code, I will take some time in future definitely and explain it.
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
// other methods..
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// initialize your other views
if (your condition){
// display header
}else{
// hide header
}
}
}
You can do some thing like this by adding header view to the item and displaying for the required set and making it gone for un necessary items.
Simply coming towards what you need, just add an empty view with layout_height="1dp" and background="#bcbcbc" like:
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#bcbcbc"/>
it'll get a line drawn for you, use it as a divider, while for making format difference just use a change text size for texts.
Hope it'll help you.
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 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);
}
}
}
I am using RecyclerView for first tab and ListView for other tabs.
when I scroll in RecyclerView it of same for ListView. but when I swipe from first tab to other tab and return to first tab I get the result as below
For the first time:
After travelling from other tab:
public class QuestionListAdapter extends RecyclerView.Adapter<QuestionListAdapter.CustomViewHolder> {
private List<QuestionListModel> feedItemList;
private Context mContext;
private String UserIDFromDatabase = "";
private ConnectionDetector connectionDetector;
public QuestionListAdapter(Context context, List<QuestionListModel> feedItemList, String UserIDFromDatabase) {
this.feedItemList = feedItemList;
this.mContext = context;
this.UserIDFromDatabase = UserIDFromDatabase;
connectionDetector = new ConnectionDetector(mContext);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.buds_profile_list_child, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
QuestionListModel feedItem = feedItemList.get(i);
// Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getQuestion()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.textView = (TextView) view.findViewById(R.id.textView_ask_question_bplc);
}
}
}
Fragment:
public class QuestionFragment extends Fragment {
ConnectionDetector connectionDetector;
View rootView;
String UserIDFromDatabase = "";
int sendToServerOffsetPub = 0;
Boolean callSuccessful = false;
private RecyclerView mRecyclerView;
private QuestionListAdapter adapter;
private com.oi.example.swipyrefreshlayout.SwipyRefreshLayout swipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.public__question_fragment, container, false);
initializeScreen();
return rootView;
}
private void initializeScreen() {
Utility.sp = getActivity().getSharedPreferences("User_Details", Context.MODE_PRIVATE);
UserIDFromDatabase = Utility.sp.getString("UserID", "");
// Initialize recycler view
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_public__question_paqf);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new QuestionListAdapter(getActivity(), Utility.arrayListQuestionListModels, UserIDFromDatabase);
mRecyclerView.setAdapter(adapter);
connectionDetector = new ConnectionDetector(getActivity());
swipeRefreshLayout = (com.oi.example.swipyrefreshlayout.SwipyRefreshLayout) rootView.findViewById(R.id.swipe_refresh_public_listview_paqf);
swipeRefreshLayout.setColorSchemeResources(R.color.color_dark_grey);
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
if (connectionDetector.isConnectingToInternet()) { // if 1
if ((Utility.publicCount > 0) && (Utility.arrayListQuestionListModels.size() > 0)) {
sendToServerOffsetPub++;
try {
callSuccessful = new getQuestionListOnProfile(getActivity(), Utility.referenceForProfileID, sendToServerOffsetPub, "PUBLIC").execute().get();
} catch (InterruptedException | ExecutionException e) {
callSuccessful = false;
}
if (!callSuccessful) {
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
} else {
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Utility.ID = (Utility.arrayListQuestionListModels.get(position).getId());
RateFeedController rateFeedController = new RateFeedController(getActivity());
ArrayList<HashMap<String, String>> DetailsArraylist = new ArrayList<HashMap<String, String>>();
DetailsArraylist = rateFeedController.getDetailsForSays(Utility.ID);
if (DetailsArraylist.size() > 0) {
String creatorID = DetailsArraylist.get(0).get("userID");
if (creatorID.equalsIgnoreCase(BudsProfileActivity.UserIDFromDatabase)) {
Utility.attachedListPPFM = 2;
}
Intent intentSays = new Intent(getActivity(), SaysScreenActivity.class);
intentSays.putExtra("ProfileBACKFLAG", "BudsProfileActivity");
startActivity(intentSays);
} else {
if (connectionDetector.isConnectingToInternet()) {// If 2
new GetFromServer(getActivity(), Integer.toString(Utility.ID), BudsProfileActivity.UserIDFromDatabase).execute();
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}// End of If 2
}
}
}));
}
}
Don't know what was wrong, but I just remove the parent Layout SwipyRefreshLayout and the My issue get solved..