I have a custom view called TinderStackLayout.
At a certain part of the code I am deleting a child view of it and re-adding it back at the last position possible -
private void handleViewAfterAnimation(View view, boolean shouldSkipView) {
Log.d("card view - ", "inside handleViewAfterAnimation");
isCardAnimating = false;
TinderStackLayout tinderStackLayout = (TinderStackLayout) view.getParent();
if (tinderStackLayout == null)
return;
tinderStackLayout.removeView(view);
if (shouldSkipView)
tinderStackLayout.addCard((TinderCardView) view, tinderStackLayout.getChildCount() - 1);
//this part is for debugging purpose
for (int i = 0; i < tinderStackLayout.getChildCount(); i++) {
View childAt = tinderStackLayout.getChildAt(i);
if (childAt instanceof TinderCardView)
Log.d("card view - ", "child cards after deletion - " + (((TinderCardView) childAt).usernameTextView.getText()));
}
}
here is my addCard() method -
public void addCard(TinderCardView tinderCardView, int addToPosition) {
View topCard = getChildAt(0);
if (topCard != null && topCard.equals(tinderCardView)) {
return;
}
topCardOnStack = tinderCardView;
ViewGroup.LayoutParams layoutParams;
layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
addView(tinderCardView, addToPosition, layoutParams);
// tinderCardView.animate()
// .x(0)
// .setInterpolator(new AnticipateOvershootInterpolator());
}
What I don't understand is what I get in the UI -
I have 3 cards.
I press the button, one card is being animated away, the second one is being shown. I press the button again, the second one animates away. I press the last one and the button does not work anymore. What I want to achieve is the first card appearing now behind the last one.
Here is what I get when logging the values out -
seems correct, it was before clicking 3 2 1 and now 2 3 1. The next one should be 1 2 3, but this is what I get for the next one -
goes back to 3 2 1 instead of 1 2 3. I can't figure out why. ?
Edit:
found the reason why this is happening, I am giving a view which should always be the top card on the stack but I am actually not giving the top card because I am always adding a new card. Here is the method -
public void handleButtonPressed(int buttonTag) {
Log.d("card view - ", "inside handleButtonPressed");
TinderStackLayout tinderStackLayout = ((TinderStackLayout) this.getParent());
TinderCardView topCard = (TinderCardView) tinderStackLayout.getChildAt(tinderStackLayout.getChildCount() - 1);
if (isCardAnimating) {
return;
}
switch (buttonTag) {
case DELETE_BUTTON_PRESSED:
isCardAnimating = true;
deleteCard(topCard);
break;
case PASS_BUTTON_PRESSED:
Log.d("card view - ", "inside pass button pressed");
isCardAnimating = true;
passCard(topCard);
Log.d("card view - ", "top card Value before pass - " + topCard.displayNameTextView.getText());
Log.d("card view - ", "child count - " + tinderStackLayout.getChildCount());
for (int i = 0; i < tinderStackLayout.getChildCount(); i++) {
View childAt = tinderStackLayout.getChildAt(i);
if (childAt instanceof TinderCardView)
Log.d("card view - ", "child cards before deletion - " + (((TinderCardView) childAt).usernameTextView.getText()));
}
break;
case APPROVE_BUTTON_PRESSED:
showLawyerContactDetailsFragment(topCard);
break;
}
}
I am trying to do TinderCardView topCard = (TinderCardView) tinderStackLayout.getChildAt(tinderStackLayout.getChildCount() - 1) in order to get the top card in my stack, which would be correct if I delete the cards and not re-add them to my stack but that is not the case when re-adding them. What should be the solution for always getting the top card when I am adding new views all the time?
If you want to shuffle cards, then you don't need to delete and re-add them. You simply need a data structure, which will do it for you. For your use case you can use Circular Array.
private CircularArray cardArray; //declaration
Now when you are adding your views, add it to your card array also.
cardArray.addLast(tinderCardView);
addView(tinderCardView); // add to your layout.
Then use this code to check.
int shuffleCount = 3;
for (int i = 1; i <= shuffleCount; i++)
shuffleTopCard(i);
Finally shuffleTopCard() method.
private void shuffleTopCard(int shuffleID) {
Log.d(TAG, "shuffleTopCard: cards before shuffle");
for (int i = 0; i < cardCount; i++)
Log.d(TAG, "shuffleTopCard: " + ((TinderCardView) cardArray.get(i)).getTag());
TinderCardView cardView = (TinderCardView) cardArray.popLast();
Log.e(TAG, "shuffleTopCard: top cardID = " + cardView.getTag());
cardArray.addFirst(cardView);
Log.d(TAG, "shuffleTopCard: cards after shuffling " + shuffleID + " time");
for (int i = 0; i < cardArray.size(); i++)
Log.d(TAG, "shuffleTopCard: " + ((TinderCardView) cardArray.get(i)).getTag());
Log.e(TAG, "shuffleTopCard: after shuffle top card = " + ((TinderCardView) cardArray.getLast()).getTag());
}
Use of CircularArray will free you from head-ache of maintaining card position manually and also separates your CustomViewGroup and card shuffling logic thereby resulting in loosely-coupled code.
Related
how can I limit the number of checked checkboxes in android? I have multiple checkboxes being added programatically and it's difficult to keep track of them.
here's the code used to add them:
final CheckBox currentVariantCheckbox = new CheckBox(getApplicationContext());
checkBoxGroupList.add(currentVariantCheckbox);
Log.d(TAG, "onDataChange: added " + currentVariantCheckbox + " to the checkboxgrouplist; size = " + checkBoxGroupList.size());
currentVariantCheckbox.setChecked((Boolean) currentVariant.child("checked").getValue());
LinearLayout checkboxGroupLayout = new LinearLayout(getApplicationContext());
checkboxGroupLayout.setOrientation(LinearLayout.HORIZONTAL);
currentVariantCheckbox.setText(currentVariant.child("name").getValue(String.class));
TextView currentVariantPriceTag = new TextView(getApplicationContext());
checkboxGroupLayout.addView(currentVariantCheckbox);
if (currentVariant.child("price").exists()) {
currentVariantPriceTag.setText("+" + currentVariant.child("price").getValue(float.class).toString() + " €");
checkboxGroupLayout.addView(currentVariantPriceTag);
ok so instead of using a onCheckedStateChangedLister I used OnClickListener. And I created an ArrayList to keep track of all the checked checkboxes:
final ArrayList<CheckBox> checkedList = new ArrayList<>();//this is the list to keep track of checked checkboxes
int maxOptions = 3
int minOptions = 1
currentVariantCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean currentCheckState = currentVariantCheckbox.isChecked();
if (currentCheckState) {//if the clicked checkboxes was unchecked and is now checked
checkedList.add(currentVariantCheckbox);
Log.d(TAG, "onClick: added " + currentVariantCheckbox + " ;checkedList.size is now: " + checkedList.size());
if (checkedList.size() >= maxOptions) {
checkedList.get(0).setChecked(false);
checkedList.remove(0);// if limit exceeded remove the first element from the checked list
Log.d(TAG, "onCheckedChanged: checkedList's size is now: " + checkedList.size());
}
} else if (checkedList.size() <= minOptions) {
currentVariantCheckbox.setChecked(true);
// if the list is empty just add the clicked checkbox to the list for example here 0
// and it will be checked automatically
} else {
checkedList.remove(currentVariantCheckbox);
// if the checkbox was already checked and no limit is exceeded
// then it will be unchecked therfore it should be removed from checkedList
}
}
});
i am having two different arraylist of diffrent size,my problem is that i have to retrieve values from both the list and show that on to a textview,when i am using two loops it is first completing the inner loop and than executing outer loop and the vales are getting printed two times and if using break to break the inner loop it is completely ignoring inner loop after 1st loop.
ArrayList<LocationDto>location = new ArrayList<>();
education<EducationDto> = new ArrayList<>();
if (education.size() != 0) {
for (int j = 0; j < education.size(); j++) {
for (int k = 0; k < location.size(); k++) {
if (!education.get(j).getSpecializationTitle().equalsIgnoreCase("") && !location.get(k).getLocationName().equalsIgnoreCase("")) {
tvEducation.append(education.get(j).getEducationTitle() + "(" + education.get(j).getSpecializationTitle() + ")" + " Located at " + location.get(k).getLocationName());
} else if (education.get(j).getSpecializationTitle().equalsIgnoreCase("") && !location.get(k).getLocationName().equalsIgnoreCase("")) {
tvEducation.append(education.get(j).getEducationTitle() + " Located at " + location.get(j).getLocationName());
} else if (!education.get(j).getSpecializationTitle().equalsIgnoreCase("") && location.get(k).getLocationName().equalsIgnoreCase("")) {
tvEducation.append(education.get(j).getEducationTitle() + "(" + education.get(j).getSpecializationTitle() + ")");
} else {
tvEducation.append(education.get(j).getEducationTitle());
}
if (j != education.size() - 1) {
tvEducation.append(" , ");
}
break;
}
}
} else {
tvEducation.setText("Not Specified");
tvEducation.setTextColor(getResources().getColor(R.color.color_three));
}
what should i do now?
The break statement terminates a loop regardless of whether it has completed or not, so your problem is that you've put a break directly inside your inner for loop without some sort of condition. Therefore the first time the loop runs it will reach the break which is why it's terminating on the first iteration!
You probably mean to put the break inside the last if statement?
I need to add views programmatically to FlexboxLayout and for each view added check if it created a new row or not.
How can I get Row count?
Tried:
for (int i = 0; i < 100; i++) {
flexboxlayout.add(createView(this.getContext(), i));
//log
Log.e("position: " + i + " ; row count -> " + flexboxlayout.getFlexLines().size());
}
getFlexLines method does not always return the expected Line count.
I am populating new data in my RecyclerView adapter all at once, so there are no insert or remove one item actions.
So simply, i have an old list and when some Event occurs i get the new list and i can assign the new list to the old.
Problems are i cannot make properly the animation for each item in the old list
when item has new position in the new list (should notifyItemMoved from old position to new)
when there is a new item in the new list (should notifyItemInserted with that position in the new list)
when the old item is not present in the new list (should notifyItemRemoved with that position)
Here is something i have now, which i thought will work for first case - item move to new position:
if(currentAdapterData!= null){
for(int i = 0; i < currentAdapterData.size(); i++){
for(int j = 0; j < newData.size(); j++){
if(currentAdapterData.get(i).getSomeIdentifier().equals(newData.get(j).getSomeIdentifier())){
Log.v("same item", "currentAdapterData index :" + i + " ," + currentAdapterData.get(i).getSomeIdentifier() + " == newData index: " + j + " ," + newData.get(j).getSomeIdentifier());
if(i != j){
notifyItemMoved(i, j);
}
}
}
}
}
currentAdapterData = newData;
However it does not work as expected, and there is difference between logs(which are correct) and the list appearing on the phone(with wrong items positions, some duplicates, buggy etc.)
So how can i make it work? With notifyItemMoved, notifyItemInserted and notifyItemRemoved?
I don't want to just use NofifyDataSetChanged, because it refresh the entire list instead of just updating the items with animations that have changed.
It looks like that your new data is also a form of list, not a single item. I think this could be a good candidate for using DiffUtil in the support library.
Here is also a nice tutorial for it.
It will allow you to calculate the difference in the new data and only update needed fields. It will also offload the work asynchronously.
You just need to implement a DiffUtil.Callback to indicate if your items are the same or the contents are the same.
You update your recyclerView like that:
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
diffResult.dispatchUpdatesTo(yourAdapter);
Simply use DiffUtil like
final MyDiffCallback diffCallback = new MyDiffCallback(prevList, newList);
final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
Create a Callback by extending MyDiffCallback and override methods and do as needed.
public class MyDiffCallback extends DiffUtil.Callback
// override methods
Well for this ,I feel this would be the easiest.Just follow it ->
Replace this
if(currentAdapterData!= null){
for(int i = 0; i < currentAdapterData.size(); i++){
for(int j = 0; j < newData.size(); j++){
if(currentAdapterData.get(i).getSomeIdentifier().equals(newData.get(j).getSomeIdentifier())){
Log.v("same item", "currentAdapterData index :" + i + " ," + currentAdapterData.get(i).getSomeIdentifier() + " == newData index: " + j + " ," + newData.get(j).getSomeIdentifier());
if(i != j){
notifyItemMoved(i, j);
}
}
}
}
}
currentAdapterData = newData;
with
if(currentAdapterData!= null){
for(int i = 0; i < currentAdapterData.size(); i++){
for(int j = 0; j < newData.size(); j++){
if(currentAdapterData.get(i).getSomeIdentifier().equals(newData.get(j).getSomeIdentifier())){
Log.v("same item", "currentAdapterData index :" + i + " ," + currentAdapterData.get(i).getSomeIdentifier() + " == newData index: " + j + " ," + newData.get(j).getSomeIdentifier());
if(i != j){
notifyDataSetChanged();
new CountDownTimer(250, 250) {
#Override
public void onTick(long millisUntilFinished) {
Log.d("millisUntilFinished", "" + millisUntilFinished);
}
#Override
public void onFinish() {
notifyItemMoved(i, j);
}
}.start();
}
}
}
}
}
this will update the values and after 250 millisecond(1/4th a second),the value with be moved with animation.
I have the following code:
for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
View v = linearLayout.getChildAt(i);
Standard.Loge("REMOVING: " + i + " " + (v == null));
linearLayout.removeViewAt(i);
}
This outputs the following:
REMOVING: 0 false
REMOVING: 1 false
REMOVING: 2 true
the app crashes, even though the views at index 2 - 4 have not been removed, throwing this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:4937)
at android.view.ViewGroup.removeViewAt(ViewGroup.java:4899)
at (((The last line in the for loop above)))
It would appear that the views are null, even though getChildCount registers that the views exist, and my guess is that this is causing removeChildAt to crash. I am adding the views dynamically in java so I am not able to use findViewByID. I am really at a loss here. How can I fix this crash so I can remove these views?
I think you actually just want to remove element 0. When you remove one of the elements, they all shift back. So element 1 becomes 0 and 2 becomes 1, etc.
This code should work:
for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
View v = linearLayout.getChildAt(0);
Standard.Loge("REMOVING: " + 0 + " " + (v == null));
linearLayout.removeViewAt(0);
}