Horizontal RecyclerView with variable item heights not wrapping properly - android

What I intend to achieve
The item view should occupy the entire height of the item
It could be that the item height is lesser than the height of the tallest item in the recyclerview, in which case it should just stick to the top like in the screenshot above.
The bug I'm running into
As in the screenshot above, views are getting truncated.
What I've tried so far
Initially I went with wrap_content on the recyclerview, now that it is supported. It didn't work when none of the views visible on the screen at the time were the tallest. This makes sense in how the view hierarchy is laid out. How can the height of something which hasn't even been bound to any data yet be calculated if the height is dependent on that data?
Workaround time :S
Instead of trying a custom layoutmanager, I first went with what I felt needed to be done - laying out all item views at the beginning to figure out their height.
There's a progressbar and an animation playing in the upper part of the screen to catch the user's attention while all this happens with recyclerview visibility set to invisible. I use two things, one didn't suffice - I've attached an observer in the adapter's onViewAttached() call and I've used a scroll change listener as well. There's a LinearSnapHelper attached to the recycler view to snap to adjacent (next or previous, depending on the scroll direction) position on scroll.
In this setup,
I'm going to each position in the recyclerview using layoutManager.smoothScrollToPosition()
Getting the child view height using
View currentChildView = binding.nextRv.getChildAt(layoutManager.findFirstCompletelyVisibleItemPosition());
if (currentChildView != null) {
currentChildHeight = currentChildView.getHeight();
}
in scroll change listener on RecyclerView.SCROLL_STATE_IDLE or by passing the height to the view attached observer mentioned above in the adapter's onViewAttachedToWindow()
#Override
public void onViewAttachedToWindow(BindingViewHolder holder) {
if (mObserver != null) {
mObserver.onViewAttached(holder.binding.getRoot().getHeight());
}
}
Storing a maxHeight that changes to the max of maxHeight and new child's height.
As is evident, this is ugly. Plus it doesn't give me the current view's height - onAttached means it's only just attached, not measured and laid out. It is the recycled view, not the view bound to current data item. Which presents problems like the truncation of view illustrated above.
I've also tried wrap_content height on the recycler view and invalidating from recycler's parent till the recycler and the child on scroll coming to SCROLL_STATE_IDLE. Doesn't work.
I'm not sure how a custom layoutmanager can help here.
Can someone guide me in the right direction?

I could not accept #Pradeep Kumar Kushwaha's answer because against one solution, I do not want different font sizes in the list. Consistency is a key element in design. Second alternative he gave couldn't work because with ellipsize I would need to give a "more" button of some sort for user to read the entire content and my text view is already taking a click action. Putting more some place else would again not be good design.
Changing the design with the simple compromise of resizing the recyclerview when the tallest, truncated item comes into focus, it turns into the simple use case of notifyItemChanged(). Even for the attempt I made using the view attached observer and scroll state listener, notifyItemChanged could be used but that approach is just too hacky. This I can live with in both code and design. Here goes the code required.
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int position = ((LinearLayoutManager) binding.nextRv.getLayoutManager())
.findFirstVisibleItemPosition();
if (position != nextSnippetAdapter.getItemCount() - 1) {
binding.nextRv.getAdapter().notifyItemRangeChanged(position, 2);
} else {
binding.nextRv.getAdapter().notifyItemChanged(position);
}
}
}
For my particular setup, calling for just these two elements works. It can further be optimized so as to call for single element at position + 1 in most cases, and checking and calling for the appropriate one in corner (literal) cases.

Inside your adapter where I can find two cards one on top and another on bottom
How I would have defined my layout is like this:
Cardview1
LinearLayout1 --> orientation vertical
cardview2 (Top card where text is written)
Linearlayout2 (where I can see icons such as like etc)-->orientation horizontal
Now fix the height of Linearlayout2 by setting it to wrap content.
And the height of cardview2 should be 0dp and add weight = 1
Now inside cardview2 add a TextView1 to matchparent in height and width.
Better inside textview1 add ellipsize to end and add max lines
If you want to show all lines try to find autoresizetextview library it can be founded here --> AutoResizeTextView
Hope it helps.

I think the recyclerview can be set to height wrap_content. And the items can be make like height to match_parent.
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layput_height="wrap_content"/>
Item as:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
// your coode
</androidx.constraintlayout.widget.ConstraintLayout>
I had little more requirement than the question. Even my problem solved in the way.
Remember I am using:
androidx.recyclerview:recyclerview:1.0.0-beta01
dependency for the project

Related

Android RecyclerView add horizontal gape in beginning and in ending

I am trying to replicate a view from iOS so that user have same look and feel throughout the android application as well.
I am having a RecyclerView with LinearLayoutManager and horizontal orientation. So far so good.
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
tools:listitem="#layout/item_recycler_view" />
With the output design:
However, in case of iOS design we have items starting from center however the horizontal view is completely scrollable (meaning the scrolling can be done to full width even if the item loading from center).
I know there is no use of adding padding/margin or using a different view like HorizontalScrollView. How can we obtain such behaviour so that i give nearly same experience to users.
Let me know if there is anything that i can provide to clarify the problem statement.
Quick solution
Add an empty item on the beginning and one on the end of your list, and make your index access account for those two extra items. That should help you get the desired effect.
Not so quick solution
Android allows us to write our own custom Layout Managers for RecyclerView. It comes with three types that will cover most of the user cases:
LinearLayoutManger (For lists in general);
GridLayoutManager (For grids);
StaggeredGridLayoutManager (For grids with items with custom sizes).
I believe you could write one to always start placing the first item on the center of the screen. That will require more work, but it won't mess with your data indexes.
Read this, and this, on how to create custom Layout Managers. Also, take a look at the docs. That should be a good place to start.
There are two ways you could do this. The simplest by far would be to add horizontal padding to your RecyclerView and set the view to not clip based on padding. Something like this:
android:paddingLeft="100dp"
android:paddingRight="100dp"
android:clipToPadding="false"
The other way would be to create an ItemDecoration and add it to your RecyclerView. You could then override the getItemOffsets() method to add a left-hand offset to your first item and a right-hand offset to your last item.
This second approach is better because it won't affect the RecyclerView's scrollbars, but it is a little more complex. Here's an example to get you started:
private static class MyItemDecoration extends RecyclerView.ItemDecoration {
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int parentWidth = parent.getWidth();
int childWidth = view.getWidth();
int margin = (parentWidth - childWidth) / 2;
int position = parent.getChildAdapterPosition(view);
outRect.left = position == 0 ? margin : 0;
outRect.right = position == (parent.getAdapter().getItemCount() - 1) ? margin : 0;
}
}
I think the only way will be adding different layout for first and last position in adapter of recyclerview.
It can be done using viewType parameter in createViewHolder(ViewGroup parent, int viewType)

RecyclerView item with layout_weight=1

Resume:
I have a ChatActivity that's basic a RecyclerView. In my chat_row_layout, i have a horizontal LinearLayout (width = wrap_content) with 2 TextViews, one of then with layout_weight = 1.
My problem :
When scrolling the recycler, some of my views width get messed up because of the recycling.
Is there some way to fix that? Ex. Force the adapter to get the original view measures
Ps: sorry for the bad formating + lack of info (i'm on phone)

How to center RecyclerView in the center (and without scrolling) when possible?

This is a short question:
Suppose I have a RecyclerView that has undefined number of items, what should I do to it, so that if there is a small number of items that (all) can fit the screen, they will be centered and the user won't be able to scroll ?
Of course, if there are too many items, that cannot fit the screen, I would like to have the RecyclerView to show them all as normal (from the beginning to how much it can show, and allow to scroll).
To understand what I mean, I think such a thing is possible when using ScrollView (or HorizontalScrollView if in horizontal), together with a LinearLayout that sets the gravity to be centered .
OK, I think I've found a way:
first, we wait for the RecyclerView to finish its layout process, as I've found about here .
Then, you need to check which child views are shown (available in the LayoutManager that you use), and look at the first and last ones.
If both of them are exactly the same as those that of the total items, it means all needed views are shown, so I can add margins on both sides of the RecyclerView (or padding on its container), according to the space that's left.
I found one complicate way to achieve that.
Main concept: set the height of RV dynamicly in code
RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
rv.setAdapter(new MySlideUpAdapter());
rv.setLayoutManager(new LinearLayoutManager(this));
ViewGroup.LayoutParams layoutParams = rv.getLayoutParams();
layoutParams.height=100;
rv.setLayoutParams(layoutParams);
You may need to calculate the RV's height by childcount*childheight to get pricise value. And don't forget to compare the height to the Parent Layout height, make sure RV's height is less than its Parent Layout height.
Here is my Layout
<RelativeLayout...>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_centerInParent="true"
android:layout_width="match_parent"
<-height will be changed in code, ignore the 50dp->
android:layout_height="50dp">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>

Dynamically Setting RelativeLayout.LayoutParams.addRule

I have this issue where I have a relative layout that has two child relative layouts (leftpanel and rightpanel). They're inside a custom layout for listview items and each item is updated from a json response from the server. So the size depends on what the server provides.
Issue: I want to have each panel's height to match each other, but it seems that setting layout_height to match_parent doesn't work (actually, if this can be resolved, then no more problems).
What I did: I programmatically set the align top and bottom of each panel to each other -- if the other's bigger, adjust the other one and vice versa. So what I did was to have a view (rightpanel) to listen to rightPanel.getViewTreeObserver().addOnScrollChangedListener(), and call the method below everytime there's a scroll change:
private void updateLayoutAlignmentParams(ViewHolder viewHolder) {
RelativeLayout.LayoutParams leftPanelLayoutParams = (RelativeLayout.LayoutParams)viewHolder.leftPanel.getLayoutParams();
RelativeLayout.LayoutParams rightPanelLayoutParams = (RelativeLayout.LayoutParams)viewHolder.rightPanel.getLayoutParams();
int leftPanelHeight = viewHolder.leftPanel.getHeight();
int rightPanelHeight = viewHolder.rightPanel.getHeight();
if(leftPanelHeight > rightPanelHeight) {
rightPanelLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, 0);
rightPanelLayoutParams.addRule(RelativeLayout.ALIGN_TOP, 0);
leftPanelLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, viewHolder.rightPanel.getId());
leftPanelLayoutParams.addRule(RelativeLayout.ALIGN_TOP, viewHolder.rightPanel.getId());
} else {
leftPanelLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, 0);
leftPanelLayoutParams.addRule(RelativeLayout.ALIGN_TOP, 0);
rightPanelLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, viewHolder.leftPanel.getId());
rightPanelLayoutParams.addRule(RelativeLayout.ALIGN_TOP, viewHolder.leftPanel.getId());
}
}
What happens: not all the views get updated while scrolling; so I get a lop-sided listview item where one is bigger than the other vertically but some do adjust well. Odd thing is, when the item gets out of view, it's lop-sided, then gets corrected consistently.
Note: I also tried
addOnDrawListener() - every item is updated but I get an ArrayList out of bounds index but doesn't point to any line in my code. Wouldn't be the best solution anyway as I need to support devices with API < 16.
setOnGlobalLayoutListener() - Nothing happens.
Please let me know if you know why or have a better solution.
Finally [kindof] fixed it! Replaced the whole method with the code below:
private void updateLayoutAlignmentParams(ViewHolder viewHolder) {
viewHolder.rightPanel.setMinimumHeight(viewHolder.leftPanel.getHeight());
viewHolder.leftPanel.setMinimumHeight(viewHolder.rightPanel.getHeight());
}
Although, I was able to achieve having the left and right panel aligned with each other using the code above. I'm now having issues where the previous view's height and width are retained when I switch views. :(
Edit:
Okay, I ended up using LinearLayout to wrap the whole listview item. Not really sure why RelativeLayout isn't complying with match_parent, though.

How to change a header TextView Text when during scrolling of Horizontal scrollView?

I have a horizontal scroll view, I also have a relativelayout as it's child. I am adding child views of this relativelayout dynamically. I have a header text which should be update when I scroll according to respective child views. How can I do this because I am able to get the current focused item in horizontal scroll. Please give me some suggestion or examples which can be helpful for me, thanks..
You should specify an OnTouchListener for your HorizontalScrollView and in it's onTouch() method detect the type of MotionEvent and change your TextView's color to the appropriate
If you are creating this childs dinamically you can set a tag to them with the content you want to show in the header TextView.
//Creating RelativeLayout childs
TextView newChild = new TextView(this).
newChild.setTag(textToShowWhenThisItemIsFocused);
Then if you know which item is focused you just have to get the tag.
// "selected" is the focused view
header.setText((String) selected.getTag());
When to use the second code depends on your implementation. Since you didn't provide any code it's hard to know how to monitor the scroll, but i.e. you could control Touch Events and update the header when the user is moving his finger over the screen (you should also take into account the inertia after the user stops tapping).
EDIT: How to get the focused View
First of all, I barely have experience doing things like this, so I'm not sure if this is going to work or if there are better ways to do it. I'll just tell you the way I would approach this problem.
To be able to know the focused View you need to know the coordinates where this View should be. Since it's an horizontal ScrollView we will need the X coordinate. Since we want the View in the middle of the ScrollView I would do it like this:
private int centerSV;
private ScrollView mScrollView;
...
centerSV = mScrollView.getWidth()/2;
Now we have the center of the ScrollView. Now we need to know which child is in this position:
private int getFocusedChildId(){
for(int i=0; i<mChilds.length; i++){
int childLeftCoord = mChilds[i].getLeft() - mScrollView.getScrollX();
if(childLeftCoord <= centerSV && centerSV <= childLeftCoord + mChilds[i].getWidth())
return mChilds[i].getId();
}
// No view found in the center, maybe ScrollView wasn't full. Return the first one
return mChilds[0].getId();
}
Again, I'm not sure if this is going to work, it's just an idea of how to approach your issue. Also, you should take this into account:
getWidth() and getHeight() of View returns 0

Categories

Resources