Implement an scroll to select an item ListView - android

I want to use an ListView where you scroll the list to select an item.
It should be like a Seekbar but the thumb should be fixed and you must use the bar to adjust it. One problem am facing is, I have no idea how this kind of widget is called, making it hard for me to search. So I made this image below to give you an better idea. And to be fair, I don't even know if this is the right title for this kind of feature.
I usually see this kind of interface in clock setting (see below image)

Reference scroll horizontal at https://stackoverflow.com/a/38411582/5887320 by use RecyclerView instead of ListView.
This is my customize code to get virtical scroll :
1.dimens.xml
<dimen name="item_dob_width">100dp</dimen>
<dimen name="item_dob_height">50dp</dimen>
2.recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/tv_year"
android:layout_width="#dimen/item_dob_width"
android:layout_height="#dimen/item_dob_height"
android:textColor="#android:color/white"
android:background="#android:color/darker_gray"
android:textSize="28sp"
android:gravity="center"/>
</LinearLayout>
3.recyclerview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</LinearLayout>
4.MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity{
private static final String TAG = MainActivity.class.getSimpleName();
public float firstItemHeightDate;
public float paddingDate;
public float itemHeightDate;
public int allPixelsDate;
public int finalHeightDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
getRecyclerviewDate();
}
public void getRecyclerviewDate() {
final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.recycler_view);
if (recyclerViewDate != null) {
recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
setDateValue();
}
}, 300);
/*recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
setDateValue();
}
}, 5000);*/
}
ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeightDate = recyclerViewDate.getMeasuredHeight();
itemHeightDate = getResources().getDimension(R.dimen.item_dob_height);
paddingDate = (finalHeightDate - itemHeightDate) / 2;
firstItemHeightDate = paddingDate;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerViewDate.setLayoutManager(dateLayoutManager);
recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
calculatePositionAndScrollDate(recyclerView);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixelsDate += dy;
}
});
if (labelerDates == null) {
labelerDates = new ArrayList<>();
}
genLabelerDate();
dateAdapter = new DateAdapter(labelerDates, (int) firstItemHeightDate);
recyclerViewDate.setAdapter(dateAdapter);
dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
return true;
}
});
}
private void genLabelerDate() {
for (int i = 0; i < 32; i++) {
LabelerDate labelerDate = new LabelerDate();
labelerDate.setNumber(Integer.toString(i));
labelerDates.add(labelerDate);
if (i == 0 || i == 31) {
labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
} else {
labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
}
}
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
if (expectedPositionDate == -1) {
expectedPositionDate = 0;
} else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
expectedPositionDate--;
}
scrollListToPositionDate(recyclerView, expectedPositionDate);
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
float targetScrollPosDate = expectedPositionDate * itemHeightDate + firstItemHeightDate - paddingDate;
float missingPxDate = targetScrollPosDate - allPixelsDate;
if (missingPxDate != 0) {
//recyclerView.smoothScrollBy((int) missingPxDate, 0);//horizontal
recyclerView.smoothScrollBy(0, (int) missingPxDate);//virtical
}
setDateValue();
}
//
private void setDateValue() {
int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
int setColorDate = expectedPositionDateColor + 1;
//set color here
dateAdapter.setSelecteditem(setColorDate);
}
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingHeightDate = 0;
private int selectedItem = -1;
public DateAdapter(ArrayList<LabelerDate> dateData, int paddingHeightDate) {
this.dateDataList = dateData;
this.paddingHeightDate = paddingHeightDate;
}
#Override
public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
parent, false);
return new DateViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
parent, false);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.height = paddingHeightDate;
view.setLayoutParams(layoutParams);
return new DateViewHolder(view);
}
}
#Override
public void onBindViewHolder(DateViewHolder holder, int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
holder.tvDate.setText(labelerDate.getNumber());
holder.tvDate.setVisibility(View.VISIBLE);
Log.d(TAG, "default " + position + ", selected " + selectedItem);
if (position == selectedItem) {
Log.d(TAG, "center" + position);
holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
holder.tvDate.setTextSize(35);
} else {
holder.tvDate.setTextColor(Color.BLACK);
holder.tvDate.setTextSize(18);
}
} else {
holder.tvDate.setVisibility(View.INVISIBLE);
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return dateDataList.size();
}
#Override
public int getItemViewType(int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (labelerDate.getType() == VIEW_TYPE_PADDING) {
return VIEW_TYPE_PADDING;
} else {
return VIEW_TYPE_ITEM;
}
}
public class DateViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public DateViewHolder(View itemView) {
super(itemView);
tvDate = (TextView) itemView.findViewById(R.id.tv_year);
}
}
}
private class LabelerDate {
private int type;
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
}

Related

Android ImageView is rendering Bitmap images smaller while in ListView

I have a ListView, inside a linear layout, that should show items based on a list_item.xml layout file. In the layout file I have two ImageViews and two TextViews. I'm using my custom ArrayAdapter to fill the ListView at runtime with Bitmap images of scale 125x25, however images are showing smaller than their initial size when rendered by the ImageView inside the ListView as shown in the screenshot (of a single list item) below:
ActivityLayout.xml:
...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:paddingTop="40dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
List_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="?android:attr/listPreferredItemHeight">
<ImageView
android:id="#+id/imageViewplate"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:adjustViewBounds="true"
android:minWidth="300dp" />
<TextView
android:id="#+id/lblListItem_letter"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/imageViewplate"
android:padding="3dp"
android:text="A"
android:textSize="17dip" />
<TextView
android:id="#+id/lblListItem_num"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/lblListItem_letter"
android:padding="3dp"
android:text="123456"
android:textSize="17dip" />
<ImageView
android:id="#+id/imageViewchars"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:paddingTop="3dp"
android:paddingBottom="3dp" />
</RelativeLayout>
My custom list adapter:
package bi.anpr.layouts;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sxx.vlctest.R;
import java.util.ArrayList;
import bi.anpr.agents.Plate;
public class PlateListAdapter extends ArrayAdapter<Plate>{
public PlateListAdapter(Context context, int resource) {
super(context, resource);
}
private ArrayList<Plate> dataSet;
Context mContext;
private static class ViewHolder {
public ImageView imageView_plate, imageView_chars;
public TextView textView_letter, textView_numbers;
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Plate plate = getItem(position);
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.textView_letter = (TextView) convertView.findViewById(R.id.lblListItem_letter);
viewHolder.textView_numbers = (TextView) convertView.findViewById(R.id.lblListItem_num);
viewHolder.imageView_plate = (ImageView) convertView.findViewById(R.id.imageViewplate);
viewHolder.imageView_chars = (ImageView) convertView.findViewById(R.id.imageViewchars);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
try{
viewHolder.imageView_plate.setImageBitmap(plate.getEngPartImageIcon());
viewHolder.imageView_chars.setImageBitmap(plate.getcharsImageIcon());
viewHolder.textView_letter.setText(Character.toString(plate.getPlateLetter()));
viewHolder.textView_numbers.setText(plate.getPlateNumbersAsString());
}catch (Exception e){
e.printStackTrace();
}
// Return the completed view to render on screen
return convertView;
}
}
Plate.java:
package bi.anpr.agents;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import java.io.Serializable;
import java.util.ArrayList;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import bi.anpr.core.IPHelper;
public class Plate implements Serializable {
private String platePath;
private boolean isWidePlate = true;
private int[] color;
private String colorString;
private String source = "";
private Rect bdgbx;
private Mat srcImage;
private Mat plateImage;
private Bitmap engPartImageIcon, plateImageIcon, forCutImageIcon, charsImageIcon, charsTextImageIcon;
private Mat engPartImage;
private Mat forCut;
private ArrayList<Character> plateNumberChars = new ArrayList<>();
private char plateLetterChar = '#';
private String fullPlateString = "";
private String numbersPlateString = "";
private double letterRate = 0;
private double numbersRate = 0;
private double accuracy = 0;
private int id;
private PlateRecogInfo plateRecogInfo;
private ArrayList<Bitmap> charsIcons = new ArrayList<>();
private boolean ignore = false;
private int accurayPercent = 0;
public Plate() {
plateRecogInfo = new PlateRecogInfo();
}
public void addPlateNumberChar(char c) {
plateNumberChars.add(c);
}
public Bitmap getplateImageIcon() {
return plateImageIcon;
}
public void setPlateImageIcon(Bitmap plateImageIcon) {
this.plateImageIcon = plateImageIcon;
}
public Bitmap getEngPartImageIcon() {
if (engPartImageIcon == null) {
engPartImageIcon = IPHelper.matToBitmap(engPartImage);
}
return engPartImageIcon;
}
public void setEngPartImageIcon(Bitmap engPartImageIcon) {
this.engPartImageIcon = engPartImageIcon;
}
public Mat getEngPartImage() {
return engPartImage;
}
public void setEngPartImage(Mat engPartImage) {
this.engPartImage = engPartImage;
}
public boolean isWidePlate() {
return isWidePlate;
}
public void setWidePlate(boolean isWidePlate) {
this.isWidePlate = isWidePlate;
}
public Mat getImage() {
return plateImage;
}
public void setImage(Mat Bitmap) {
plateImage = Bitmap;
}
public Bitmap getForCutImageIcon() {
if (forCutImageIcon == null) {
forCutImageIcon = IPHelper.matToBitmap(forCut);
}
return forCutImageIcon;
}
public Mat getForCut() {
return forCut;
}
public void setForCutImageIcon(Bitmap forCutImageIcon) {
this.forCutImageIcon = forCutImageIcon;
}
public void setForCut(Mat forCut) {
this.forCut = forCut;
}
public ArrayList<Character> getPlateNumberChar() {
return plateNumberChars;
}
public void setPlateNumberChar(ArrayList<Character> nchar) {
plateNumberChars = new ArrayList<Character>(nchar);
}
public char getPlateLetter() {
return plateLetterChar;
}
public void setPlateLetter(char plateLetter) {
plateLetterChar = plateLetter;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getLetterRate() {
return letterRate;
}
public void setLetterRate(double letterRate) {
this.letterRate = letterRate;
}
public double getCharsRate() {
return numbersRate;
}
public void setNumbersRate(double NumbersRate) {
this.numbersRate = NumbersRate;
}
public double getAccuracy() {
return accuracy;
}
public int getAccurayPercent() {
return accurayPercent;
}
public void setAccuracy(double totalRate) {
this.accuracy = totalRate;
this.accurayPercent = (int) (totalRate * 100);
}
public Mat getPlateImage() {
return plateImage;
}
public void setPlateImage(Mat matImage) {
this.plateImage = matImage;
plateImageIcon = IPHelper.matToBitmap(matImage);
}
public PlateRecogInfo getPlateRecogInfo() {
return plateRecogInfo;
}
public void setPlateRecogInfo(PlateRecogInfo plateRecogInfo) {
this.plateRecogInfo = plateRecogInfo;
}
public void addCharIcon(Mat charsIcons) {
this.charsIcons.add(IPHelper.matToBitmap(charsIcons));
}
public Bitmap getcharsImageIcon() {
if (charsImageIcon == null) {
int width = 5;
int height = 0;
for (Bitmap icon : charsIcons) {
if (icon.getHeight() > height)
height = icon.getHeight();
width += icon.getWidth() + 5;
}
height += 6;
charsImageIcon = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(charsImageIcon);
int i = 0;
for (Bitmap icon : charsIcons) {
canvas.drawBitmap(icon, i, 3, null);
i += icon.getWidth() + 5;
}
}
return charsImageIcon;
}
public Bitmap getCharsTextImageIcon() {
if (charsTextImageIcon == null) {
String chars = "";
for (Character c : plateNumberChars) {
String cs = c.toString();
chars += cs;
}
int width = 5;
int height = 0;
for (Bitmap icon : charsIcons) {
if (icon.getHeight() > height)
height = icon.getHeight();
width += icon.getWidth() + 5;
}
height += 6;
charsTextImageIcon = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(charsTextImageIcon);
int i = 0;
int j = 0;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
paint.setColor(Color.BLACK);
paint.setTextSize(16);
canvas.drawColor(Color.WHITE);
for (Bitmap icon : charsIcons) {
if (j == 0)
canvas.drawText("Some Text", i + 2, 19, paint);
else
canvas.drawText(Character.toString(chars.charAt(j - 1)), i + 3, 19, paint);
i += icon.getWidth() + 5;
j++;
}
}
return charsTextImageIcon;
}
public void setCharsTextImageIcon(Bitmap charsTextImageIcon) {
this.charsTextImageIcon = charsTextImageIcon;
}
public Mat getSrcImage() {
return srcImage;
}
public void setSrcImage(Mat srcImage) {
this.srcImage = srcImage;
}
public Rect getBdgbx() {
return bdgbx;
}
public void setBdgbx(Rect bdgbx) {
this.bdgbx = bdgbx;
}
public int[] getColor() {
return color;
}
// public Color getColorObject() {
// int[] color = getColor();
//
// try {
// return Color.parseColor(Color.rgb(color[0], color[1], color[2]));
// } catch (Exception e) {
// }
// return null;
// }
public void setColor(int[] is) {
this.color = is;
}
public String getColorString() {
return colorString;
}
public void setColorString(String colorString) {
this.colorString = colorString;
}
public String getFullPlateCharsString() {
if (fullPlateString == "" || fullPlateString == null) {
fullPlateString += plateLetterChar;
for (Character c : plateNumberChars) {
fullPlateString += c.toString();
}
}
return fullPlateString;
}
public void setFullPlateString(String fullPlateString) {
this.fullPlateString = fullPlateString;
}
public void setNumbersPlateString(String numbersPslateString) {
this.numbersPlateString = numbersPslateString;
}
public String getPlateNumbersAsString() {
if (numbersPlateString == "" || numbersPlateString == null) {
for (Character c : plateNumberChars) {
numbersPlateString += c.toString();
}
}
return numbersPlateString;
}
public String getPlatePath() {
return platePath;
}
public void setPlatePath(String platePath) {
this.platePath = platePath;
}
public boolean isIgnore() {
return ignore;
}
public void setIgnore(boolean ignore) {
this.ignore = ignore;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}
Usage:
PlateListAdapter plateListAdapter = new PlateListAdapter(getApplicationContext(), R.layout.list_item);
ListView resultsListView = (ListView) findViewById(R.id.lvExp);
resultsListView.setAdapter(plateListAdapter);
plateListAdapter.addAll(recogInfo.getPlates());
plateListAdapter.notifyDataSetChanged();
Using definite dimensions for ImageView's, rather than wrap_content solved the problem.

How to change color in ExpandableRecyclerView

I am using this library but I can't get to a way to change the group background color from white.
EDIT: the xml files as requested in comments:
content_main.xml
the content_main file which include the expandable recyclerview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />
</LinearLayout>
activity_main.xml
the main activity
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#64dd17"
tools:context="ayalma.ir.sample.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
row_drawer.xml
the custom row layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffb74d">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="#dimen/carbon_toolbarHeight"
android:gravity="center_vertical"
android:paddingLeft="#dimen/carbon_padding"
android:paddingRight="#dimen/carbon_padding" />
</LinearLayout>
Add this line to your
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
tools:listitem="#layout/exr_group"
And change backgound color
Remove your previous library from Gradle
compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'
Add this library to your Gradle
compile 'com.nineoldandroids:library:2.4.0'
Copy this file to your package
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
public class ExpandableRecyclerView extends android.support.v7.widget.RecyclerView {
public ExpandableRecyclerView(Context context) {
super(context, null);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
initRecycler();
}
public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initRecycler();
}
private void initRecycler() {
setClipToPadding(false);
setItemAnimator(new DefaultItemAnimator());
}
#Override
public Parcelable onSaveInstanceState() {
//begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
//end
if (getAdapter() != null)
ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();
return ss;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
//begin boilerplate code so parent classes can restore state
if (!(state instanceof SavedState)) // if state is not instance of out SaveState just restore in reg way
{
super.onRestoreInstanceState(state);
return;
}
// else if cast him to SavedState
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
//end
if (getAdapter() != null)
((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);
}
static class SavedState implements Parcelable {
public static final SavedState EMPTY_STATE = new SavedState() {
};
SparseBooleanArray stateToSave;
Parcelable superState;
SavedState() {
superState = null;
}
SavedState(Parcelable superState) {
this.superState = superState != EMPTY_STATE ? superState : null;
}
private SavedState(Parcel in) {
Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());
this.superState = superState != null ? superState : EMPTY_STATE;
this.stateToSave = in.readSparseBooleanArray();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(#NonNull Parcel out, int flags) {
out.writeParcelable(superState, flags);
out.writeSparseBooleanArray(this.stateToSave);
}
public Parcelable getSuperState() {
return superState;
}
//required field that makes Parcelables from a Parcel
public static final Creator<SavedState> CREATOR =
new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
#Override
public void setAdapter(android.support.v7.widget.RecyclerView.Adapter adapter) {
if (!(adapter instanceof Adapter))
throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");
super.setAdapter(adapter);
}
public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {
private OnChildItemClickedListener onChildItemClickedListener;
private static final int TYPE_HEADER = 0;
SparseBooleanArray expanded = new SparseBooleanArray();
public Adapter() {
}
boolean isExpanded(int group) {
return expanded.get(group);
}
SparseBooleanArray getExpandedGroups() {
return expanded;
}
public void setExpandedGroups(SparseBooleanArray expanded) {
this.expanded = expanded;
}
public void expand(int group) {
if (isExpanded(group))
return;
// this lines of code calculate number of shown item in recycler view. also group is counting .
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i);
}
position++; // this for percent group
notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding
expanded.put(group, true); // save expanding in sparce array
}
public void collapse(int group) {
if (!isExpanded(group)) // if is not expanded . so nothing to collapse.
return;
int position = 0;
for (int i = 0; i < group; i++) {
position++;
if (isExpanded(i))
position += getChildItemCount(i); // item
}
position++;
notifyItemRangeRemoved(position, getChildItemCount(group));
expanded.put(group, false);
}
public abstract int getGroupItemCount();
public abstract int getChildItemCount(int group);
#Override
public int getItemCount() {
int count = 0;
for (int i = 0; i <= getGroupItemCount(); i++) {
count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;
}
return count;
}
public abstract G getGroupItem(int position);
public abstract C getChildItem(int group, int position);
public Object getItem(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItem(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return getGroupItem(group);
}
throw new IndexOutOfBoundsException();
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group)) {
onBindChildViewHolder((CVH) holder, group, i);
return;
}
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0) {
onBindGroupViewHolder((GVH) holder, group);
return;
}
}
throw new IndexOutOfBoundsException();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);
}
protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);
protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);
public abstract int getChildItemViewType(int group, int position);
#Override
public int getItemViewType(int i) {
int group = 0;
while (group <= getGroupItemCount()) {
if (i > 0 && !isExpanded(group)) {
i--;
group++;
continue;
}
if (i > 0 && isExpanded(group)) {
i--;
if (i < getChildItemCount(group))
return getChildItemViewType(group, i);
i -= getChildItemCount(group);
group++;
continue;
}
if (i == 0)
return TYPE_HEADER;
}
throw new IndexOutOfBoundsException();
}
public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {
this.onChildItemClickedListener = onItemClickedListener;
}
public void onBindChildViewHolder(CVH holder, final int group, final int position) {
holder.itemView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (Adapter.this.onChildItemClickedListener != null) {
Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);
}
}
});
}
public void onBindGroupViewHolder(final GVH holder, final int group) {
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).setExpanded(isExpanded(group));
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded(group)) {
collapse(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).collapse();
} else {
expand(group);
if (holder instanceof GroupViewHolder)
((GroupViewHolder) holder).expand();
}
}
});
}
}
public static abstract class GroupViewHolder extends RecyclerView.ViewHolder {
public GroupViewHolder(View itemView) {
super(itemView);
}
public abstract void expand();
public abstract void collapse();
public abstract void setExpanded(boolean expanded);
public abstract boolean isExpanded();
}
public static class SimpleGroupViewHolder extends GroupViewHolder {
ImageView expandedIndicator;
TextView text;
private boolean expanded;
public SimpleGroupViewHolder(Context context) {
super(View.inflate(context, R.layout.exr_group, null));
itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
text = (TextView) itemView.findViewById(R.id.carbon_groupText);
}
public void expand() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = true;
}
public void collapse() {
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
expandedIndicator.postInvalidate();
}
});
animator.start();
expanded = false;
}
public void setExpanded(boolean expanded) {
ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
this.expanded = expanded;
}
#Override
public boolean isExpanded() {
return expanded;
}
public void setText(String t) {
text.setText(t);
}
public String getText() {
return text.getText().toString();
}
}
public interface OnChildItemClickedListener {
void onChildItemClicked(int group, int position);
}
}
group xml copy to layout folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fefefe"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:id="#+id/carbon_groupText"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:gravity="center_vertical" />
<ImageView
android:id="#+id/carbon_groupExpandedIndicator"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_vertical"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:tint="#000000"
app:srcCompat="#drawable/ic_expand_more_24dp" />
</LinearLayout>
copy inside drawable folder
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z"/>
</vector>
Now user this inside your xml
<com.example.package.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />
instead of
<ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false" />

Dynamic Endless RecyclerView scrolling issues

I have to create following layout
So far, I have successfully created the layout and populated all views. However, I am facing problem in the making ReyclerView Endless on first fragment.
Consider the RecyclerView has 10 items on first load, now on scroll I am adding another 10 items and so on. However, the RecyclerView isn't displaying those items, it's height gets fixed at the end of 10th element. I know that the elements are loaded correctly in RecyclerView and if I try to scroll with two fingers on emulator (GenyMotion), the RecyclerView scrolls just fine.
Update :-
Code for RecyclerView's Fragment -
public class CheckInFragmentRecyclerAdapter extends RecyclerView.Adapter<CheckInFragmentRecyclerAdapter.ViewHolder> {
final List<StoreNew> stores;
public CheckInFragmentRecyclerAdapter(final List<StoreNew> stores) {
this.stores = stores;
}
#Override
public CheckInFragmentRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_check_in_fragment, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(CheckInFragmentRecyclerAdapter.ViewHolder holder, int position) {
// Setting data
}
#Override
public int getItemCount() {
return stores.size();
}
/**
* Function to clear existing data from list
* #param stores StoreNew instance containing store information
*/
public void update(final List<StoreNew> stores) {
this.stores.clear();
this.stores.addAll(stores);
notifyDataSetChanged();
}
/**
* Function to add more data to list
* #param stores StoreNew instance containing store information
*/
public void addNewList(final List<StoreNew> stores) {
this.stores.addAll(stores);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
// Initializing component
}
}
}
Update :-
Adding layouts for used screens.
main_screen.xml - This is the home screen
<android.support.v4.widget.NestedScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/home_footer"
android:layout_below="#+id/toolbar"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Sliding Tab for showing images -->
<com.example.slidingtab.SlidingTabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white" />
<!-- ViewPager for Images -->
<android.support.v4.view.ViewPager
android:id="#+id/vpOffers"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="8dp" />
<!-- Segmented Control for fragments -->
<info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
android:id="#+id/segmented2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
segmentedgroup:sc_border_width="1dp"
segmentedgroup:sc_corner_radius="4dp"
segmentedgroup:sc_tint_color="#color/black">
<RadioButton
android:id="#+id/rbTab1"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:textSize="#dimen/normal_text"
android:text="#string/check_in" />
<RadioButton
android:id="#+id/rbTab2"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="#dimen/normal_text"
android:text="#string/upload_bill" />
<RadioButton
android:id="#+id/rbTab3"
style="#style/segmented_radio_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="#dimen/normal_text"
android:text="#string/redeem" />
</info.hoang8f.android.segmented.SegmentedGroup>
<!-- Custom wrap content ViewPager containing fragments -->
<!-- This will make sure that the height of ViewPager is equal to height of Fragment -->
<com.example.ui.custom.WrapContentHeightViewPager
android:id="#+id/vpFragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
WrapContentHeightViewPager.java
public class WrapContentHeightViewPager extends ViewPager {
private static final String TAG = WrapContentHeightViewPager.class.getSimpleName();
private int height = 0;
private int decorHeight = 0;
private int widthMeasuredSpec;
private boolean animateHeight;
private int rightHeight;
private int leftHeight;
private int scrollingPosition = -1;
private boolean enabled;
public WrapContentHeightViewPager(Context context) {
super(context);
init();
}
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
init();
}
private void init() {
addOnPageChangeListener(new OnPageChangeListener() {
public int state;
#Override
public void onPageScrolled(int position, float offset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
if (state == SCROLL_STATE_IDLE) {
height = 0; // measure the selected page in-case it's a change without scrolling
Log.d(TAG, "onPageSelected:" + position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
this.state = state;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return this.enabled && super.onTouchEvent(event);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.enabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
#Override
public void setAdapter(PagerAdapter adapter) {
height = 0; // so we measure the new content in onMeasure
super.setAdapter(new PagerAdapterWrapper(adapter));
}
/**
* Allows to redraw the view size to wrap the content of the bigger child.
*
* #param widthMeasureSpec with measured
* #param heightMeasureSpec height measured
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
widthMeasuredSpec = widthMeasureSpec;
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
if(height == 0) {
// measure vertical decor (i.e. PagerTitleStrip) based on ViewPager implementation
decorHeight = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if(lp != null && lp.isDecor) {
int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
if(consumeVertical) {
decorHeight += child.getMeasuredHeight() ;
}
}
}
// make sure that we have an height (not sure if this is necessary because it seems that onPageScrolled is called right after
int position = getCurrentItem();
View child = getViewAtPosition(position);
if (child != null) {
height = measureViewHeight(child);
}
//Log.d(TAG, "onMeasure height:" + height + " decor:" + decorHeight);
}
int totalHeight = height + decorHeight + getPaddingBottom() + getPaddingTop();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY);
//Log.d(TAG, "onMeasure total height:" + totalHeight);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
public void onPageScrolled(int position, float offset, int positionOffsetPixels) {
super.onPageScrolled(position, offset, positionOffsetPixels);
// cache scrolled view heights
if (scrollingPosition != position) {
scrollingPosition = position;
// scrolled position is always the left scrolled page
View leftView = getViewAtPosition(position);
View rightView = getViewAtPosition(position + 1);
if (leftView != null && rightView != null) {
leftHeight = measureViewHeight(leftView);
rightHeight = measureViewHeight(rightView);
animateHeight = true;
//Log.d(TAG, "onPageScrolled heights left:" + leftHeight + " right:" + rightHeight);
} else {
animateHeight = false;
}
}
if (animateHeight) {
int newHeight = (int) (leftHeight * (1 - offset) + rightHeight * (offset));
if (height != newHeight) {
//Log.d(TAG, "onPageScrolled height change:" + newHeight);
height = newHeight;
requestLayout();
invalidate();
}
}
}
private int measureViewHeight(View view) {
view.measure(getChildMeasureSpec(widthMeasuredSpec, getPaddingLeft() + getPaddingRight(), view.getLayoutParams().width), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
return view.getMeasuredHeight();
}
protected View getViewAtPosition(int position) {
if(getAdapter() != null) {
Object objectAtPosition = ((PagerAdapterWrapper) getAdapter()).getObjectAtPosition(position);
if (objectAtPosition != null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null && getAdapter().isViewFromObject(child, objectAtPosition)) {
return child;
}
}
}
}
return null;
}
/**
* Wrapper for PagerAdapter so we can ask for Object at index
*/
private class PagerAdapterWrapper extends PagerAdapter {
private final PagerAdapter innerAdapter;
private SparseArray<Object> objects;
public PagerAdapterWrapper(PagerAdapter adapter) {
this.innerAdapter = adapter;
this.objects = new SparseArray<>(adapter.getCount());
}
#Override
public void startUpdate(ViewGroup container) {
innerAdapter.startUpdate(container);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = innerAdapter.instantiateItem(container, position);
objects.put(position, object);
return object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
innerAdapter.destroyItem(container, position, object);
objects.remove(position);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
innerAdapter.setPrimaryItem(container, position, object);
}
#Override
public void finishUpdate(ViewGroup container) {
innerAdapter.finishUpdate(container);
}
#Override
public Parcelable saveState() {
return innerAdapter.saveState();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
innerAdapter.restoreState(state, loader);
}
#Override
public int getItemPosition(Object object) {
return innerAdapter.getItemPosition(object);
}
#Override
public void notifyDataSetChanged() {
innerAdapter.notifyDataSetChanged();
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
innerAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
innerAdapter.unregisterDataSetObserver(observer);
}
#Override
public float getPageWidth(int position) {
return innerAdapter.getPageWidth(position);
}
#Override
public CharSequence getPageTitle(int position) {
return innerAdapter.getPageTitle(position);
}
#Override
public int getCount() {
return innerAdapter.getCount();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return innerAdapter.isViewFromObject(view, object);
}
public Object getObjectAtPosition(int position) {
return objects.get(position);
}
}
}
first_fragment.xml
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvCheckIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:requiresFadingEdge="none"
android:fadingEdgeLength="0dp"
android:orientation="vertical" />
Adding more data to the RecyclerView on scrolling -
private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = adapter.getItemCount();
firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold) && current_page < totalPages) {
// End has been reached
// Do something
current_page++;
// Sending request to server
loading = true;
}
}
};
When data is received via API (adapter already added above)-
adapter.addNewList(homePageNew.checkin_stores.stores);
There seems to be a similar discussion here: ViewPager in a NestedScrollView
Maybe the sample of the Naruto guy (https://github.com/TheLittleNaruto/SupportDesignExample/) could solve your situation.
Edit
I'm not sure if I'm getting the point of your question. Anyway here you can a possible solution to your situation.
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/app_bar_layout"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
---- include here everything before the pager ----
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
---- this is your pager
<include layout="#layout/fragment_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/app_bar_layout"
/>
</android.support.design.widget.CoordinatorLayout>
Then you can just listen to the RecycleView in the pager to add items as the RecycleView scrolls to bottom.
I hope it helped
You can see my implementation of the endless RecyclerView scroll:
GalleryActivity.java
public class GalleryActivity extends AppCompatActivity {
private StaggeredGridLayoutManager layoutManager;
private RecyclerView recyclerView;
private ImageRecyclerViewAdapter imageAdapter;
private List<ImageItem> images;
private ImageSearchClient imageSearchClient;
private String query;
private int currentStartPosition = 1;
private boolean loading = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
getSupportActionBar().setHomeButtonEnabled(true);
query = getIntent().getStringExtra(Utils.QUERY_TAG);
if (query == null)
return;
imageSearchClient = new ImageSearchClient(query);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new StaggeredGridLayoutManager(2, 1);
recyclerView.setLayoutManager(layoutManager);
images = new ArrayList<>();
imageAdapter = new ImageRecyclerViewAdapter(this, images);
recyclerView.setAdapter(imageAdapter);
recyclerView.addOnScrollListener(new EndlessRecyclerScrollListener());
loadMoreData();
}
private void loadMoreData() {
loading = true;
imageSearchClient.getService().customSearch(Utils.API_KEY, Utils.CX_KEY, query,
Utils.IMAGE_SEARCH_TYPE,
currentStartPosition,
Utils.ITEMS_COUNT,
new Callback<ImageResponse>() {
#Override
public void success(ImageResponse imageResponse, Response response) {
List<ImageItem> items = imageResponse.getItems();
for (ImageItem item : items) {
images.add(item);
}
imageAdapter.notifyDataSetChanged();
currentStartPosition += items.size();
loading = false;
}
#Override
public void failure(RetrofitError error) {
Log.e(GalleryActivity.class.getSimpleName(),
error.getResponse().getReason());
}
});
}
private class EndlessRecyclerScrollListener extends RecyclerView.OnScrollListener {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] visibleItems = layoutManager.findLastVisibleItemPositions(null);
int lastItem = 0;
for (int i : visibleItems) {
lastItem = Math.max(lastItem, i);
}
if (lastItem > 0 && lastItem > images.size() - Utils.ITEMS_COUNT && !loading) {
if (NetworkUtils.hasConnection(GalleryActivity.this)) {
loadMoreData();
} else {
Toast.makeText(GalleryActivity.this, R.string.network_error,
Toast.LENGTH_SHORT).show();
}
}
}
}
}
ImageRecyclerViewAdapter.java (nothing is extraordinary here):
public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<ImageViewHolder> {
private List<ImageItem> itemList;
private Context context;
private int parentWidth = 0;
public ImageRecyclerViewAdapter(Context context, List<ImageItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_card_item, null);
ImageViewHolder imageViewHolder = new ImageViewHolder(layoutView);
parentWidth = parent.getWidth();
return imageViewHolder;
}
#Override
public void onBindViewHolder(final ImageViewHolder holder, int position) {
Picasso.with(context)
.load(itemList.get(position).getLink())
.error(R.drawable.error_image)
.placeholder(R.drawable.progress_animation)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int targetWidth = parentWidth / 2;
float ratio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
float heightFloat = ((float) targetWidth) * ratio;
final android.view.ViewGroup.MarginLayoutParams layoutParams
= (ViewGroup.MarginLayoutParams) holder.image.getLayoutParams();
layoutParams.height = (int) heightFloat;
layoutParams.width = (int) targetWidth;
holder.image.setLayoutParams(layoutParams);
holder.image.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}

Get center visible item of RecycleView when scrolling

This is what I want:
As image above, I want to draw a center line on RecycleView, then get the center item when scrolling (as well as move left or right)
Here is my try to draw a horizontal RecycleView:
HorizontalAdapter adapter = new HorizontalAdapter(data);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recycleView.setLayoutManager(layoutManager);
recycleView.setAdapter(adapter);
Is there any way to know which item is moved to the center of RecycleView? And how can I scroll RecycleView to left or right just one position?
Update: I tried to use a scroll listener to get the middle position, but it doesn't work as an aspect.
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstPos = layoutManager.findFirstVisibleItemPosition();
int lastPos = layoutManager.findLastVisibleItemPosition();
int middle = Math.abs(lastPos - firstPos) / 2 + firstPos;
int selectedPos = -1;
for (int i = 0; i < adapter.getItemCount(); i++) {
if (i == middle) {
adapter.getItem(i).setSelected(true);
selectedPos = i;
} else {
adapter.getItem(i).setSelected(false);
}
}
adapter.notifyDataSetChanged();
}
And get the result:
I only want to change the selected item (make text to white color) when it is on the blue Rect
I made something just like this. I can do exactly what you need.
First of all, this is how is my alogrithm work
This is my recyclerView Adapter
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingWidthDate = 0;
private int selectedItem = -1;
public DateAdapter(ArrayList<LabelerDate> dateData, int paddingWidthDate) {
this.dateDataList = dateData;
this.paddingWidthDate = paddingWidthDate;
}
#Override
public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_date,
parent, false);
return new DateViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_padding,
parent, false);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.width = paddingWidthDate;
view.setLayoutParams(layoutParams);
return new DateViewHolder(view);
}
}
#Override
public void onBindViewHolder(DateViewHolder holder, int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
if(labelerDate.dateType.equals(BirthDayActivity.DateType.C31))
holder.tvDate.setText(String.valueOf(labelerDate.valueDate));
holder.tvDate.setVisibility(View.VISIBLE);
holder.imgSmall.setVisibility(View.VISIBLE);
if (position == selectedItem) {
holder.tvDate.setTextColor(Color.parseColor("#094673"));
holder.tvDate.setTextSize(35);
holder.imgSmall.setBackgroundResource(R.color.textviewbold);
} else {
holder.tvDate.setTextColor(Color.GRAY);
holder.tvDate.setTextSize(35);
holder.imgSmall.setBackgroundResource(R.color.gray);
}
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return dateDataList.size();
}
#Override
public int getItemViewType(int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (labelerDate.dateType.equals(BirthDayActivity.DateType.NONE)) {
return VIEW_TYPE_PADDING;
}
return VIEW_TYPE_ITEM;
}
public class DateViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public ImageView imgSmall;
public DateViewHolder(View itemView) {
super(itemView);
tvDate = (TextView) itemView.findViewById(R.id.tvNumberDate);
imgSmall = (ImageView) itemView.findViewById(R.id.small_marked_dob);
}
}}
This is most important alogrithm:
public void getRecyclerviewDate() {
recyclerViewDate = (RecyclerView) findViewById(R.id.recyclerViewDay);
ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
finalWidthDate = recyclerViewDate.getMeasuredWidth();
itemWidthDate = getResources().getDimension(R.dimen.item_dob_width);
paddingDate = (finalWidthDate - itemWidthDate) / 2;
firstItemWidthDate = paddingDate ;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewDate.setLayoutManager(dateLayoutManager);
recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if(newState == RecyclerView.SCROLL_STATE_IDLE){
calculatePositionAndScrollDate(recyclerView);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixelsDate += dx;
}
});
if (labelerDates == null)
labelerDates = new ArrayList<>();
labelerDates.addAll(genLabelerDate(currentMonth, currentYear));
dateAdapter = new DateAdapter(labelerDates, (int) firstItemWidthDate);
recyclerViewDate.setAdapter(dateAdapter);
return true;
}
});
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
if (expectedPositionDate == -1) {
expectedPositionDate = 0;
} else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
expectedPositionDate--;
}
scrollListToPositionDate(recyclerView, expectedPositionDate);
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
float targetScrollPosDate = expectedPositionDate * itemWidthDate + firstItemWidthDate - paddingDate;
float missingPxDate = targetScrollPosDate - allPixelsDate;
if (missingPxDate != 0) {
recyclerView.smoothScrollBy((int) missingPxDate, 0);
}
}
private void setDateValue() {
int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
setColorDate = expectedPositionDateColor + 1;
//set color here
dateAdapter.setSelecteditem(setColorDate);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
allPixelsDate = savedInstanceState.getFloat(BUNDLE_LIST_PIXELS_DATE);
allPixelsDateChanged = savedInstanceState.getFloat(BUNDLE_LIST_PIXELS_DATE_CHANGED);
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putFloat(BUNDLE_LIST_PIXELS_DATE, allPixelsDate);
outState.putFloat(BUNDLE_LIST_PIXELS_DATE_CHANGED, allPixelsDateChanged);
}
And this is my result:
Look at this video link, this is my app demo
Sometimes is needed the entire example code block together, because we may miss something. Here is what I have, feel free to correct anything since I may be doing some little mistake somewhere. And Yes, this answer is an extension of #tranhieu answer. Thanks #tranhieu.
MainActivity.java
package com.test;
import android.app.Activity;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
public float firstItemWidthDate;
public float paddingDate;
public float itemWidthDate;
public int allPixelsDate;
public int finalWidthDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRecyclerviewDate();
}
public void getRecyclerviewDate() {
final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.rv_tasks_date);
if (recyclerViewDate != null) {
recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
setDateValue();
}
}, 300);
recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
setDateValue();
}
}, 5000);
}
ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
finalWidthDate = recyclerViewDate.getMeasuredWidth();
itemWidthDate = getResources().getDimension(R.dimen.item_dob_width);
paddingDate = (finalWidthDate - itemWidthDate) / 2;
firstItemWidthDate = paddingDate;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewDate.setLayoutManager(dateLayoutManager);
recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
synchronized (this) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
calculatePositionAndScrollDate(recyclerView);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
allPixelsDate += dx;
}
});
if (labelerDates == null) {
labelerDates = new ArrayList<>();
}
genLabelerDate();
dateAdapter = new DateAdapter(labelerDates, (int) firstItemWidthDate);
recyclerViewDate.setAdapter(dateAdapter);
dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
return true;
}
});
}
private void genLabelerDate() {
for (int i = 0; i < 32; i++) {
LabelerDate labelerDate = new LabelerDate();
labelerDate.setNumber(Integer.toString(i));
labelerDates.add(labelerDate);
if (i == 0 || i == 31) {
labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
} else {
labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
}
}
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
if (expectedPositionDate == -1) {
expectedPositionDate = 0;
} else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
expectedPositionDate--;
}
scrollListToPositionDate(recyclerView, expectedPositionDate);
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
float targetScrollPosDate = expectedPositionDate * itemWidthDate + firstItemWidthDate - paddingDate;
float missingPxDate = targetScrollPosDate - allPixelsDate;
if (missingPxDate != 0) {
recyclerView.smoothScrollBy((int) missingPxDate, 0);
}
setDateValue();
}
//
private void setDateValue() {
int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemWidthDate) / itemWidthDate);
int setColorDate = expectedPositionDateColor + 1;
// set color here
dateAdapter.setSelecteditem(setColorDate);
}
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingWidthDate = 0;
private int selectedItem = -1;
public DateAdapter(ArrayList<LabelerDate> dateData, int paddingWidthDate) {
this.dateDataList = dateData;
this.paddingWidthDate = paddingWidthDate;
}
#Override
public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
parent, false);
return new DateViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
parent, false);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.width = paddingWidthDate;
view.setLayoutParams(layoutParams);
return new DateViewHolder(view);
}
}
#Override
public void onBindViewHolder(DateViewHolder holder, int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
holder.tvDate.setText(labelerDate.getNumber());
holder.tvDate.setVisibility(View.VISIBLE);
Log.d(TAG, "default " + position + ", selected " + selectedItem);
if (position == selectedItem) {
Log.d(TAG, "center" + position);
holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
holder.tvDate.setTextSize(35);
} else {
holder.tvDate.setTextColor(Color.WHITE);
holder.tvDate.setTextSize(18);
}
} else {
holder.tvDate.setVisibility(View.INVISIBLE);
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return dateDataList.size();
}
#Override
public int getItemViewType(int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (labelerDate.getType() == VIEW_TYPE_PADDING) {
return VIEW_TYPE_PADDING;
} else {
return VIEW_TYPE_ITEM;
}
}
public class DateViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public DateViewHolder(View itemView) {
super(itemView);
tvDate = (TextView) itemView.findViewById(R.id.txt_date);
}
}
}
private class LabelerDate {
private int type;
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_tasks_date"
android:layout_width="match_parent"
android:layout_height="48dp" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginTop="48dp"
android:src="#android:drawable/ic_dialog_info" />
</FrameLayout>
</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_date"
android:layout_width="#dimen/item_dob_width"
android:layout_height="48dp"
android:text="32"
android:textColor="#android:color/white"
android:background="#android:color/darker_gray"
android:textSize="28sp"
android:gravity="center"/>
</LinearLayout>
dimens.xml
<resources>
<dimen name="item_dob_width">100dp</dimen>
</resources>
Oh boy. I've been searching for this answer for almost a week and then found out the solution. Custom LayoutManagers? No. ItemDecorator? Nope.
Here's the easiest way to do it:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingStart="150dp"
android:paddingEnd="150dp"
android:clipToPadding="false" />
The critical part is:
android:paddingStart="150dp"
android:paddingEnd="150dp"
android:clipToPadding="false"
And then just assign SnapHelper to your RecylcerView:
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)
This is it. The easiest and most perfect solution to the problem
I'm used the SnapHelper right here:
// init snaphelper
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView)
// init layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(mainActivity);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
// init adapter
adatper.setSnapHelper(snapHelper);
adatper.setLayoutManager(layoutManager);
adatper.initAdapter(new Float((DisplayHelper.getDisplayWidth(mainActivity) / 2) - (fooViewWidth / 2)).intValue());
recyclerView.setAdapter(adatper);
As said by TranHieu the solution of inserting 2 item for padding (at start and at end positions) is good.
I don't like the use of ViewTreeObserver because of poor readability of code. With this technique then you must also manage redrawing of the items if they are recycled.
If you are using customview classes you can set its width directly into these classes.
For example this is my padding class
/**
* Created by firegloves on 25/09/15.
*/
#EViewGroup(R.layout.view_padding)
public class PaddingView extends FooView {
Context mCtx;
public PaddingView(Context context) {
super(context);
mCtx = context;
}
public void setWidth(int width) {
setLayoutParams(new LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
In my adapter I store the desired padding item width, that is equal to (displayWidth / 2) - (realItemWidth / 2)
This is my adapter, don't look at methods not matching RecyclerView.Adapter, pay attention to the initAdapter method and to the onCreateItemView method
#EBean
public class FooAdapterRecycler extends RecyclerViewAdapterBase<Foo, FooView> {
private final int TYPE_PADDING_VIEW = 0;
private final int TYPE_REAL_VIEW = 1;
#RootContext
Context ctx;
#Bean(Finder.class)
IFinder finder;
SnapHelper snapHelper;
RecyclerView.LayoutManager layoutManager;
private int paddingWidth = 0;
/**
* preleva i dati dal finder
*/
public void initAdapter(int paddingWidth) {
/*******************************
* THIS CODE IS THE IMPORTANT ONE
******************************/
this.paddingWidth = paddingWidth;
// add 1 item for initial space
mItems = new ArrayList<>();
Foo foo = new Foo();
mItems.add(foo);
// get real items from finder
mItems.addAll(finder.findAll());
// add 1 item for final space
mItems = new ArrayList<>();
Foo foo2 = new Foo();
mItems.add(foo2);
}
#Override
public int getItemViewType(int position) {
if (position == 0 || position == getItemCount()-1) {
return TYPE_PADDING_VIEW;
} else {
return TYPE_REAL_VIEW;
}
}
#Override
protected FooView onCreateItemView(ViewGroup parent, int viewType) {
/*******************************
* THIS CODE IS THE IMPORTANT ONE
******************************/
if (viewType == TYPE_PADDING_VIEW) {
PaddingView view = PaddingView_.build(ctx);
view.setWidth(paddingWidth);
return view;
} else {
return FooView_.build(ctx);
}
}
public void setSnapHelper(SnapHelper snapHelper) {
this.snapHelper = snapHelper;
}
public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
}
I'm using AndroidAnnotations library but it's not required
Hope that helps
USING SNAPHELPER - A SMOOTHER SOLUTION
Here it is another solution using SnapHelper. Starting from the answer of #TranHieu here:
https://stackoverflow.com/a/34647005/3944251
and the compressed by #sector11 here:
https://stackoverflow.com/a/38411582/3944251
I wrote the following code which is also based in both answers above, but it's simpler and offers a smoother solution using SnapHelper presented in android support library 24.2.0.
Here you have the MainActivity class. The rest is the same with #sector11's answer.
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public float firstItemWidthDate;
public float itemWidthDate;
public int allPixelsDate;
public int finalWidthDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
labelerDates = new ArrayList<>();
getRecyclerviewDate();
}
public void getRecyclerviewDate() {
final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.rv_tasks_date);
recyclerViewDate.postDelayed(new Runnable() {
#Override
public void run() {
//recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
setDateValue();
}
}, 300);
ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
finalWidthDate = recyclerViewDate.getMeasuredWidth();
itemWidthDate = getResources().getDimension(R.dimen.item_dob_width);
firstItemWidthDate = (finalWidthDate - itemWidthDate) / 2;
allPixelsDate = 0;
final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
dateLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewDate.setLayoutManager(dateLayoutManager);
/* Create a LinearSnapHelper and attach the recyclerView to it. */
final LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerViewDate);
recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
allPixelsDate += dx;
recyclerView.post(new Runnable() {
public void run() {
setDateValue();
}
});
}
});
genLabelerDate();
dateAdapter = new DateAdapter(labelerDates, (int) firstItemWidthDate);
recyclerViewDate.setAdapter(dateAdapter);
dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
return true;
}
});
}
private void genLabelerDate() {
for (int i = 0; i < 32; i++) {
LabelerDate labelerDate = new LabelerDate();
labelerDate.setNumber(Integer.toString(i));
labelerDates.add(labelerDate);
if (i == 0 || i == 31) {
labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
} else {
labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
}
}
}
//
private void setDateValue() {
int expectedPositionDateColor = Math.round(allPixelsDate / itemWidthDate);
int setColorDate = expectedPositionDateColor + 1;
// set color here
dateAdapter.setSelecteditem(setColorDate);
}
public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
private ArrayList<LabelerDate> dateDataList;
private static final int VIEW_TYPE_PADDING = 1;
private static final int VIEW_TYPE_ITEM = 2;
private int paddingWidthDate = 0;
private int selectedItem = -1;
public DateAdapter(ArrayList<LabelerDate> dateData, int paddingWidthDate) {
this.dateDataList = dateData;
this.paddingWidthDate = paddingWidthDate;
}
#Override
public DateAdapter.DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
if (viewType == VIEW_TYPE_PADDING) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
layoutParams.width = paddingWidthDate;
view.setLayoutParams(layoutParams);
}
return new DateViewHolder(view);
}
#Override
public void onBindViewHolder(DateAdapter.DateViewHolder holder, int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
holder.tvDate.setText(labelerDate.getNumber());
holder.tvDate.setVisibility(View.VISIBLE);
Log.d(TAG, "default " + position + ", selected " + selectedItem);
if (position == selectedItem) {
Log.d(TAG, "center" + position);
holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
holder.tvDate.setTextSize(35);
} else {
holder.tvDate.setTextColor(Color.WHITE);
holder.tvDate.setTextSize(18);
}
} else {
holder.tvDate.setVisibility(View.INVISIBLE);
}
}
public void setSelecteditem(int selecteditem) {
this.selectedItem = selecteditem;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return dateDataList.size();
}
#Override
public int getItemViewType(int position) {
LabelerDate labelerDate = dateDataList.get(position);
if (labelerDate.getType() == VIEW_TYPE_PADDING) {
return VIEW_TYPE_PADDING;
} else {
return VIEW_TYPE_ITEM;
}
}
public class DateViewHolder extends RecyclerView.ViewHolder {
public TextView tvDate;
public DateViewHolder(View itemView) {
super(itemView);
tvDate = (TextView) itemView.findViewById(R.id.txt_date);
}
}
}
private class LabelerDate {
private int type;
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
}
You can use a LinearSnapHelper
Attach to your recyclerView like
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(this)
Then, to get the center view, use
snapHelper.findSnapView(horizontalScrollView.layoutManager)?
As mentioned in the other answer, there is no direct way to do this.
This is probably how you can achieve what you described in the question.
Know the number of items visible on the screen.
Select the middle item programmatically every time the view is scrolled.
Keep a partially transparent image as an overlay on the middle item on the recyclerview. (You'll need to compute the coordinates based on the width of the recycler view or width of the screen and the width of the overlay image you choose to put.
Refresh the selected value in a text view below the recycler view every time there is a scroll.
The image overlays have to be placed in a way they appear connected and as one single control.
For this feature use EcoGallery library:
https://github.com/falnatsheh/EcoGallery
At first, I needed something similar, not this. But I was able to adapt #TranHieu solution to my needs, so I voted up his solution.
I wanted to create full-screen horizontal recyclerview that after user sroll updates scrollPosition to mostVisibleItem.
setup:
private void setUpScrolling() {
mRecyclerVIew.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
mRecyclerVIew.getViewTreeObserver().removeOnPreDrawListener(this);
CustomScrollListener listener = (CustomScrollListener) mScrollListener;
listener.width = mRecyclerVIew.getMeasuredWidth();
listener.dx = 0;
return true;
}
});
}
listener:
private class CustomScrollListener extends OnScrollListener {
private int mLastDx = 0;
int width = 0;
int dx = 0;
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (mLastDx != dx) {
scrollToMostVisibleItem();
} else {
dx = 0;
mLastDx = 0;
}
}
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
this.dx += dx;
}
private void scrollToMostVisibleItem() {
int direction = (dx > 0) ? 1 : -1;
dx = Math.abs(dx);
int shiftCount = Math.round(dx / width);
int pixelShift = dx % width;
if (pixelShift > width / 2) {
shiftCount++;
}
float targetScrollPixels = shiftCount * width;
float finalScrollPixels = (targetScrollPixels - dx) * direction;
if (finalScrollPixels != 0) {
mRecyclerVIew.smoothScrollBy((int) finalScrollPixels, 0);
mLastDx = (int) finalScrollPixels;
dx = 0;
}
}
}
I used another approach in my case.
you can find the deatils here: RecyclerView - How highlight central visible item during scroll1
In my opinion, my solution is more easy than the others.
If someone is looking for a more generic implementation, here is my code based on the answers of this thread:
Add the CenterLinearSnapHelper
public class CenterLinearSnapHelper extends LinearSnapHelper {
//Constants
public static final String TAG = CenterLinearSnapHelper.class.getSimpleName();
//Attributes
private Context context;
private float itemWidth;
private OnPaddingComputationListener listener;
//Constructors
/**
* A linear snap helper which helps centering the items in a recyclerview.
*
* #param itemWidth The (fixed) width of a child view in pixels.
*/
public CenterLinearSnapHelper(float itemWidth) {
this.itemWidth = itemWidth;
}
public void attachToRecyclerView(#Nullable RecyclerView recyclerView,
#NonNull OnPaddingComputationListener listener) throws IllegalStateException {
this.listener = listener;
//Calculates the padding for the first and end item
calculatePadding(recyclerView);
//Create a LinearSnapHelper and attach the recyclerView to it.
attachToRecyclerView(recyclerView);
}
public float getItemWidth() {
return itemWidth;
}
private void calculatePadding(RecyclerView recyclerView) {
if (recyclerView == null)
return;
ViewTreeObserver observer = recyclerView.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
int finalWidth = recyclerView.getMeasuredWidth();
float padding = (finalWidth - itemWidth) / 2;
listener.onPadding(padding, finalWidth);
return true;
}
});
}
public interface OnPaddingComputationListener {
void onPadding(float padding, int finalWidth);
}
}
In your Activity/Fragment where you create your RecyclerView:
float itemWidth = getResources().getDimension(R.dimen.favorite_room_width);
CenterLinearSnapHelper snapHelper = new CenterLinearSnapHelper(itemWidth);
snapHelper.attachToRecyclerView(binding.listFavorites, (padding, finalWidth) -> {
//Set the adapter
roomAdapter = new RoomAdapter(requireContext(), rooms);
roomAdapter.addPaddingItems((int) padding);
roomAdapter.setOnToggleClickListener(FavoritesFragment.this);
binding.listFavorites.setAdapter(roomAdapter);
});
In your adapter:
public void addPaddingItems(int padding) {
if (padding < 0)
throw new IllegalStateException("Padding cannot be smaller than 0");
this.padding = padding;
//Add 2 new items as the first and last
//NOTE: If you update your existing dataset (e.g add new items), you should redo the calculation!
rooms.add(0, new Room("First"));
rooms.add(rooms.size(), new Room("Last"));
}
#Override
public int getItemViewType(int position) {
if (padding >= 0 && (position == 0 || position == rooms.size() - 1)) {
return VIEW_TYPE_PADDING;
}
return VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RoomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ViewFavoriteRoomBinding binding = DataBindingUtil.inflate(inflater, R.layout.view_favorite_room, parent, false);
if (viewType == VIEW_TYPE_PADDING) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) binding.getRoot().getLayoutParams();
layoutParams.width = padding;
binding.getRoot().setLayoutParams(layoutParams);
}
RoomViewHolder viewHolder = new RoomViewHolder(context, binding, onToggleClickListener);
viewHolder.getRecyclerView().setRecycledViewPool(viewPool);
return viewHolder;
}

Hide View Propotional to RecyclerView Scrolling

In my android application I have a recyclerview and LinearLayout. LinearLayout lies on the top and recyclerview lies down to the linearlayout. what my requirement is when recyclerview starts scrolls the last item, the linearlayout should start hide in propotion to scroll amount.
I have done a little and it works. but it is not proportional to the scroll amount. here is my code
ScrollListener
public class MyScrollListener extends OnScrollListener {
private LinearLayoutManager mLayoutManager;
public MyScrollListener(LinearLayoutManager manager) {
this.mLayoutManager = manager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (visibleItemCount + firstVisibleItem >= totalItemCount) {
scrollTheShit(dy * -1, ((View) recyclerView.getChildAt(visibleItemCount - 1)).getWidth());
}
}
public void scrollTheShit(int dy, int widthOfLastChild) {}
}
MainActivity
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.container);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager mgr = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mgr);
recyclerView.setAdapter(new RecyclerAdapter());
recyclerView.addOnScrollListener(new MyScrollListener(mgr) {
#Override
public void scrollTheShit(int dy, int widthOfLastChild) {
linearLayout.setY(linearLayout.getY() + dy );
}
});
}
private class RecyclerAdapter extends Adapter<RecyclerAdapter.ViewHolder> {
#Override
public int getItemCount() {
return 10;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder,
int position) {
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View v = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.child, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View arg0) {
super(arg0);
}
}
}
}
I have to hide the top section when the below RecyclerView scrolls
how do I correct this ? anyone please help me
this may help you
QuickReturnRecyclerView.java
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
public class QuickReturnRecyclerView extends RecyclerView {
private static final String TAG = QuickReturnRecyclerView.class.getName();
private View mReturningView;
private static final int STATE_ONSCREEN = 0;
private static final int STATE_OFFSCREEN = 1;
private static final int STATE_RETURNING = 2;
private int mState = STATE_ONSCREEN;
private int mMinRawY = 0;
private int mReturningViewHeight;
private int mGravity = Gravity.BOTTOM;
public QuickReturnRecyclerView(Context context) {
super(context);
init();
}
public QuickReturnRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public QuickReturnRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
}
/**
* The view that should be showed/hidden when scrolling the content.
* Make sure to set the gravity on the this view to either Gravity.Bottom or
* Gravity.TOP and to put it preferable in a FrameLayout.
* #param view Any kind of view
*/
public void setReturningView(View view) {
mReturningView = view;
try {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mReturningView.getLayoutParams();
mGravity = params.gravity;
} catch (ClassCastException e) {
throw new RuntimeException("The return view need to be put in a FrameLayout");
}
measureView(mReturningView);
mReturningViewHeight = mReturningView.getMeasuredHeight();
addOnScrollListener(new RecyclerScrollListener());
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
private class RecyclerScrollListener extends OnScrollListener {
private int mScrolledY;
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(mGravity == Gravity.BOTTOM)
mScrolledY += dy;
else if(mGravity == Gravity.TOP)
mScrolledY -= dy;
if(mReturningView == null)
return;
int translationY = 0;
int rawY = mScrolledY;
switch (mState) {
case STATE_OFFSCREEN:
if(mGravity == Gravity.BOTTOM) {
if (rawY >= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
} else if(mGravity == Gravity.TOP) {
if (rawY <= mMinRawY) {
mMinRawY = rawY;
} else {
mState = STATE_RETURNING;
}
}
translationY = rawY;
break;
case STATE_ONSCREEN:
if(mGravity == Gravity.BOTTOM) {
if (rawY > mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
} else if(mGravity == Gravity.TOP) {
if (rawY < -mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
}
translationY = rawY;
break;
case STATE_RETURNING:
if(mGravity == Gravity.BOTTOM) {
translationY = (rawY - mMinRawY) + mReturningViewHeight;
if (translationY < 0) {
translationY = 0;
mMinRawY = rawY + mReturningViewHeight;
}
if (rawY == 0) {
mState = STATE_ONSCREEN;
translationY = 0;
}
if (translationY > mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
} else if(mGravity == Gravity.TOP) {
translationY = (rawY + Math.abs(mMinRawY)) - mReturningViewHeight;
if (translationY > 0) {
translationY = 0;
mMinRawY = rawY - mReturningViewHeight;
}
if (rawY == 0) {
mState = STATE_ONSCREEN;
translationY = 0;
}
if (translationY < -mReturningViewHeight) {
mState = STATE_OFFSCREEN;
mMinRawY = rawY;
}
}
break;
}
/** this can be used if the build is below honeycomb **/
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
TranslateAnimation anim = new TranslateAnimation(0, 0, translationY, translationY);
anim.setFillAfter(true);
anim.setDuration(0);
mReturningView.startAnimation(anim);
} else {
mReturningView.setTranslationY(translationY);
}
}
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<yourpackagename.QuickReturnRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#android:color/darker_gray"
android:orientation="horizontal"
android:padding="15dp">
<Button
android:id="#+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:layout_weight="1"
android:text="New Button" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_weight="1"
android:text="New Button" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:layout_weight="1"
android:text="New Button" />
</LinearLayout>
</FrameLayout>
in MainActivity.java just add below lines
mRecyclerView = (QuickReturnRecyclerView) findViewById(R.id.recycler_view);
linear = (LinearLayout) findViewById(R.id.linear);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setReturningView(linear);

Categories

Resources