Unable to Pass Data from RecyclerView Adapter to Viewpager Adapter - android-recyclerview

I am creating simple image gallery app in which images are shown on MainActivity inside RecyclerView and on click of Any Image it will take us to SlideActivity in which I want to show images on ViewPager and then we swipe all images should be shown on ViewPager. For retrieving images i am using Glide. Images Load on RecyclerView Perfectly Fine but when i click on any Image i get this Exception "java.lang.ArrayIndexOutOfBoundsException: length=15; index=-1".
I know there are many same questions like this I saw all codes but did not understood so finally decided to ask question I am pasting code whatever i tried till now. Any Suggestion or advice will be helpful bcz I work alone I have no Mentor and I am Learning. Thank you!
Error :
java.lang.ArrayIndexOutOfBoundsException: length=15; index=-1
at java.util.ArrayList.get(ArrayList.java:439)
at com.starmoonsolutions.imagegallery.RecycleViewAdapter$ViewHolder$1.onClick(RecycleViewAdapter.java:63)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
ImageUrl.java
public class ImageUrl {
String imageUrl;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
RecyclerView recyclerView;
GridLayoutManager gridLayoutManager;
ArrayList<ImageUrl> imageUrlList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
recyclerView = findViewById(R.id.recyclerView);
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
imageUrlList = prepareData();
RecycleViewAdapter galleryAdapter = new RecycleViewAdapter(getApplicationContext(), imageUrlList);
recyclerView.setAdapter(galleryAdapter);
}
private ArrayList prepareData(){
// here you should give your image URLs and that can be a link from the Internet
String imageUrls[] = {
"https://images.pexels.com/photos/358457/pexels-photo-358457.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
"https://images.pexels.com/photos/934964/pexels-photo-934964.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/1202887/pexels-photo-1202887.jpeg?auto=compress&cs=tinysrgb&h=650&w=940",
"https://images.pexels.com/photos/337909/pexels-photo-337909.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/894443/pexels-photo-894443.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/951325/pexels-photo-951325.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/1534411/pexels-photo-1534411.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/266436/pexels-photo-266436.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/1894350/pexels-photo-1894350.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/87009/earth-soil-creep-moon-lunar-surface-87009.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/1820563/pexels-photo-1820563.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"https://images.pexels.com/photos/1274260/pexels-photo-1274260.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
};
imageUrlList = new ArrayList<>();
for (int i = 0; i < imageUrls.length; i++) {
ImageUrl imageUrl = new ImageUrl();
imageUrl.setImageUrl(imageUrls[i]);
imageUrlList.add(imageUrl);
}
Log.d("MainActivity", "List count: " + imageUrlList.size());
return imageUrlList;
}
}
RecyclerViewAdapter:
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder>{
private ArrayList<ImageUrl> imageUrls;
private Context context;
public RecycleViewAdapter(Context context, ArrayList<ImageUrl> imageUrls) {
this.imageUrls = imageUrls;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_layout, viewGroup, false);
return new ViewHolder(view);
}
/**
* gets the image url from adapter and passes to Glide API to load the image
*
* #param viewHolder
* #param i
*/
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Glide.with(context).load(imageUrls.get(i).getImageUrl()).into(viewHolder.img);
}
#Override
public int getItemCount() {
return imageUrls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
RecyclerView recyclerView;
ImageView img;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imageView);
recyclerView = itemView.findViewById(R.id.recyclerView);
final int pos = getAdapterPosition();
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SlideActivity.class);
error point here-> intent.putExtra("image", String.valueOf(imageUrls.get(pos).getImageUrl())); <- error point here
intent.putExtra("position", pos);
intent.putExtra("list", imageUrls.get(pos).imageUrl);
context.startActivity(intent);
}
});
}
}
}
SlideActivity(ViewPager):
public class SlideActivity extends AppCompatActivity {
private ViewPager viewPager;
private Context context = SlideActivity.this;
private ViewPagerAdapter adapter;
private ArrayList<String> list;
String image;
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_activity);
viewPager = findViewById(R.id.viewPager);
getIntentInfo();
adapter = new ViewPagerAdapter(list,context);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem((position));
}
private void getIntentInfo() {
image = getIntent().getStringExtra("image");
list = getIntent().getStringArrayListExtra("list");
position = getIntent().getIntExtra("position",0);
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
private ArrayList<String> imageUrls;
private android.content.Context context;
private LayoutInflater inflater;
private ImageView wallpaper;
public ViewPagerAdapter() {
}
public ViewPagerAdapter(ArrayList<String> imageUrls, android.content.Context context) {
this.imageUrls = imageUrls;
this.context = context;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view.equals(o);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View view = inflater.inflate(R.layout.pager_item, container, false);
wallpaper = view.findViewById(R.id.walpaperImage);
Glide.with(context).asBitmap().load(imageUrls.get(position)).into(wallpaper);
container.addView(view, 0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}

The problem is actually in getting the adapter position.
public ViewHolder(#NonNull final View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imageView);
recyclerView = itemView.findViewById(R.id.recyclerView);
// remove the below line
//final int pos = getAdapterPosition();
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SlideActivity.class);
// you need to freshly get the adapter position here.
int pos = getAdapterPosition();
error point here-> intent.putExtra("image", String.valueOf(imageUrls.get(pos).getImageUrl())); <- error point here
intent.putExtra("position", pos);
intent.putExtra("list", imageUrls.get(pos).imageUrl);
context.startActivity(intent);
}
});
}
Since ViewHolder gets recycled, adapter position can change therefore you need to get the latest adapter position inside your click listener.
And regarding the Bundle data, pass the list of URLs of 'String' type instead of the custom object,
public void onClick(View v) {
Intent intent = new Intent(context, SlideActivity.class);
error point here-> intent.putExtra("image", String.valueOf(imageUrls.get(pos).getImageUrl())); <- error point here
intent.putExtra("position", pos);
// imageUrls is of type ArrayList<String>
intent.putStringArrayListExtra("list", imageUrls);
context.startActivity(intent); }
or else use the Parcelable library to serialize the custom object.

Related

how fix NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
im new in android programing and i want to add JSON to my recyclerview i was getting the adapter not attetched skiping layout but my CustomAdapter is giving me NullPointerException too.
my CustomAdapter
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroProduct> dataList;
private Context context;
CustomAdapter(Context context, List< RetroProduct > dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
final View mView;
TextView goodsId,categoryTitle,number,title1,title2;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
goodsId = mView.findViewById(R.id.tv_goodsId);
categoryTitle = mView.findViewById(R.id.tv_categoryTitle);
number = mView.findViewById(R.id.tv_number);
title1 = mView.findViewById(R.id.tv_title1);
title2 = mView.findViewById(R.id.tv_title2);
}
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_row, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.goodsId.setText(dataList.get(position).getGoodsId());
holder.categoryTitle.setText(dataList.get(position).getCategoryTitle());
holder.title1.setText(dataList.get(position).getTitle1());
holder.title2.setText(dataList.get(position).getTitle2());
holder.number.setText(dataList.get(position).getNumber());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
and im getting NullPointerException on
return dataList.size();
what should i do now? give it value or i dont know.
MainActivity
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataService service =
RetrofitClientInstance.getRetrofitInstance()
.create(GetDataService.class);
Call< List<RetroProduct> > call = service.getAllProducts();
call.enqueue(new Callback<List<RetroProduct>>() {
#Override
public void onResponse(Call<List<RetroProduct>> call,
Response<List<RetroProduct>> response) {
generateDataList(response.body());
LinearLayoutManager manager = new
LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<RetroProduct>> call, Throwable t)
{
Toast.makeText(MainActivity.this, "null",
Toast.LENGTH_SHORT).show();
}
});
}
private void generateDataList(List<RetroProduct> productList) {
recyclerView = findViewById(R.id.recycler_view);
adapter = new CustomAdapter(this,productList);
}
}
#Override
public int getItemCount() {
if(dataList!=null)
return dataList.size();
else
return 0;
}
Add a null check before calling size() method of a Arraylist as above

change background of all textviews in recyclerview from activity and not from adapter

I have a recyclerview with a textview and the clicked textview gets a background around it.I also have a button within the activity which should put a background to all the items in the recyclerview ie..to show all selected.I am putting my activity and adapter code.please help me
my activity code
set_all_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommonUtility.selectedDays.clear();
CommonUtility.selectedDays.addAll(daysList);
//loadDays();
}
});
my adapter
public class DaysAdapter<T> extends RecyclerView.Adapter<DaysAdapter.ViewHolder> {
private ArrayList<String> list=new ArrayList<>();
private Context mContext;
private RecyclerViewClickListener mListener;
public DaysAdapter(ArrayList<String> data, Context context, RecyclerViewClickListener listener) {
list = data;
//languageListFiltered = filteredData;
mContext = context;
mListener = listener;
}
#Override
public void onBindViewHolder(DaysAdapter.ViewHolder viewHolder, final int position) {
viewHolder.titleTextView.setText(list.get(position));
// viewHolder.lang_radio.setChecked(position == mSelectedItem);
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mContext);
final View view = inflater.inflate(R.layout.days_list_item, viewGroup, false);
return new ViewHolder(view);
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ViewHolder(final View inflate) {
super(inflate);
titleTextView = (TextView)inflate.findViewById(R.id.text_day);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!CommonUtility.selectedDays.contains(titleTextView.getText().toString()))
{
titleTextView.setBackground(mContext.getResources().getDrawable(R.drawable.green_circle));
titleTextView.setTextColor(mContext.getResources().getColor(R.color.white));
CommonUtility.selectedDays.add(titleTextView.getText().toString());
Log.d("added",titleTextView.getText().toString());
}
else
{
int index=CommonUtility.selectedDays.indexOf(titleTextView.getText().toString());
CommonUtility.selectedDays.remove(index);
titleTextView.setBackground(null);
Log.d("removed",titleTextView.getText().toString());
titleTextView.setTextColor(mContext.getResources().getColor(R.color.black));
}
}
};
itemView.setOnClickListener(clickListener);
titleTextView.setOnClickListener(clickListener);
}
}
}

Android Studio : E/RecyclerView: No adapter attached; skipping layout

I've found only a few articles related to this issue on StackOverflow tried all of their solutions in various combinations but can't get the RecyclerView to display my RecyclerView.Adapter that is populated with data which a I can verify and see the list in debug mode but it simply won't show the information.
My code (I struggled to paste the XML Layout files):
public class RecipeDetailActivity extends AppCompatActivity {
private RecipeModel mRecipe;
private ArrayList<IngredientModel> mIngredientList = new ArrayList<>();
private IngredientListAdapter ingredientListAdapter;
private RecyclerView rvIngredientList;
private boolean mTwoPane;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_detail);
rvIngredientList = (RecyclerView)findViewById(R.id.rv_ingredient_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvIngredientList.setLayoutManager(layoutManager);
SampleRecycler sampleRecycler = new SampleRecycler(); // empty RecyclerView.Adapter
rvIngredientList.setAdapter(sampleRecycler);
mRecipe = getIntent().getParcelableExtra("com.wernerraubenheimer.bakingapp.data.RecipeModel");
mIngredientList = mRecipe.getIngredients();
ingredientListAdapter = new IngredientListAdapter(mIngredientList);
ingredientListAdapter.notifyDataSetChanged();
// Up until this point the RecyclerVie.Adapter is populated with data - debug mode I can see the list
rvIngredientList.swapAdapter(ingredientListAdapter, false);
}
}
public class IngredientListAdapter extends RecyclerView.Adapter<IngredientListAdapter.IngredientViewHolder> {
private ArrayList<IngredientModel> mIngredientList;
private Context mContext;
private boolean mTwoPane;
public IngredientListAdapter(ArrayList<IngredientModel> ingredientList) {
mIngredientList = ingredientList;
}
#Override
public IngredientViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
int layoutIdForListItem = R.layout.ingredient_list_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean attachImmediatelyToParent = false;
View view = inflater.inflate(layoutIdForListItem, parent, attachImmediatelyToParent);
IngredientViewHolder viewHolder = new IngredientViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(IngredientViewHolder holder, int position) {
IngredientModel ingredient = mIngredientList.get(position);
holder.bind(mContext, ingredient);
}
#Override
public int getItemCount() {
if (mIngredientList != null) {
return 0;
} else {
return mIngredientList.size();
}
}
static class IngredientViewHolder extends RecyclerView.ViewHolder {
private CardView cardviewContainer;
private TextView tvIngredientName;
private TextView tvIngredientQuantity;
private TextView tvIngredientMeasure;
private Context mContext;
private IngredientModel mIngredient;
IngredientViewHolder(View itemView) {
super(itemView);
//cardviewContainer = (CardView)itemView.findViewById(R.id.card_view_ingredient);
tvIngredientName = (TextView)itemView.findViewById(R.id.text_view_ingredient_name);
tvIngredientQuantity =(TextView)itemView.findViewById(R.id.text_view_quantity);
tvIngredientMeasure = (TextView)itemView.findViewById(R.id.text_view_measure);
}
void bind(Context context, IngredientModel ingredientModel) {
mContext = context;
mIngredient = ingredientModel;
tvIngredientName.setText(mIngredient.getIngredient());
tvIngredientQuantity.setText(mIngredient.getQuantity());
tvIngredientMeasure.setText(mIngredient.getMeasure());
}
}
}
Although, it is difficult to decipher from the code you have pasted,
it looks like the problem is with the following function:
#Override
public int getItemCount() {
if (mIngredientList != null) {
return 0;
} else {
return mIngredientList.size();
}
}
Changing condition to if (mIngredientList == null) { should solve the problem.
Also, in the RecipeDetailActivity.onCreate() method, only following code should be enough to display the list:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_detail);
rvIngredientList = (RecyclerView) findViewById(R.id.rv_ingredient_list);
rvIngredientList.setLayoutManager(new LinearLayoutManager(this));
mRecipe = getIntent().getParcelableExtra("com.wernerraubenheimer.bakingapp.data.RecipeModel");
mIngredientList = mRecipe.getIngredients();
ingredientListAdapter = new IngredientListAdapter(mIngredientList);
rvIngredientList.setAdapter(ingredientListAdapter);
}

How to play the song when an item is clicked in recyclerView (no buttons)?

I am creating a music app and I have listed my songs in RecyclerView. What I want is when I click any song(inside the red marked area), the song should play, just like in modern music players. I don't want any play, stop buttons on my RecyclerView. Any help would be appreciated! Thanks in advance!
Songs.java
public class Songs extends Fragment {
private static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
SongInfoModel s;
private MediaPlayer mediaPlayer;
ScaleInAnimationAdapter alphaAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_activity, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
mediaPlayer = new MediaPlayer();
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
SongInfoModel s= new SongInfoModel("Cheap Thrills","Sia",null, null,
"http://mp3fb.com/wp-includes/inc/down.php?
id=hyCQomZzosfGBvVON0tRV7xfiL2GdtKXbTsBrZh_3NM&t=Sia%2B-
%2BCheap%2BThrils%2B%D0%A0%D0%B5%D0%BC%D0%B8%D0%BA%D1%81.mp3
&hash=true",null,null);
SongList.add(s);
songAdapter = new SongAdapter(getContext(),SongList);
alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
alphaAdapter.setDuration(1000);
alphaAdapter.setInterpolator(new OvershootInterpolator());
alphaAdapter.setFirstOnly(false);
recyclerView.setAdapter(alphaAdapter);
Collections.sort(SongList, new Comparator<SongInfoModel>(){
public int compare(SongInfoModel a, SongInfoModel b){
return a.getSongName().compareTo(b.getSongName());
}
});
return view;
}
SongAdapter.java:
public class SongAdapter extends
RecyclerView.Adapter<SongAdapter.SongHolder>
{
ArrayList<SongInfoModel> SongList = new ArrayList<>();
Context context;
MediaPlayer mediaPlayer;
SongInfoModel obj;
public SongAdapter(Context context, ArrayList<SongInfoModel> SongList) {
this.context = context;
this.SongList = SongList;
}
#Override
public SongAdapter.SongHolder onCreateViewHolder(ViewGroup parent, int
viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row_song,
parent, false);
return new SongHolder(view);
}
#Override
public void onBindViewHolder(final SongAdapter.SongHolder holder, final
int
position) {
final SongInfoModel songInfoModel = SongList.get(position);
holder.songName.setText(songInfoModel.SongName);
holder.artistName.setText(songInfoModel.ArtistName);
}
#Override
public int getItemCount() {
return SongList.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName;
TextView artistName;
TextView duration;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView)itemView.findViewById(R.id.SongName);
artistName= (TextView)itemView.findViewById(R.id.ArtistName);
duration = itemView.findViewById(R.id.duration);
}
}
}
First, Create an Interface in Adapter class like this -
private CustomOnClickListener customOnClickListener;
public interface CustomOnClickListener{
void onClick(int position);
}
After that Implement View.OnClickListener in View holder class
class TracksViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TracksViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
customOnClickListener.onClick(getAdapterPosition());
}
After that Implement CustomOnClickListener in your Fragment or Activity class.

android only show first viewpager inside recyclerview

i have a viewpager with FragmentStatePagerAdapter inside recyclerview
and its show only the first row in recyclerview
please help me
viewpager adapter:
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
public CustomPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
Log.e("fragmentManager",fragmentManager.toString());
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment currentFragment;
switch (position) {
case 0:
currentFragment=new FirstFragment();
break;
case 1:
currentFragment=new SecondFragment();
break;
case 2:
currentFragment=new ThirdFragment();
break;
default:
currentFragment=new FirstFragment();
break;
}
return currentFragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
recyclerview adapter:
public class JobAdapter extends RecyclerView.Adapter<JobAdapter.JobHolder> {
private Context context;
private List<String> mJobList = new ArrayList<>();
public JobAdapter(List<String> mJobList,Context context) {
this.mJobList = mJobList;
this.context=context;
}
#Override
public JobHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.find_job_line_content, parent, false);
return new JobHolder(view);
}
#Override
public void onBindViewHolder(final JobHolder holder, int position) {
configurePagerHolder(holder, position);
}
private void configurePagerHolder(JobHolder holder, int position) {
//Job job= mJobList.get(position);
CustomPagerAdapter adapter = new CustomPagerAdapter(((MainActivity)context).getSupportFragmentManager());
holder.viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
holder.viewPager.setCurrentItem(1);
Log.e("configurePagerHolder",position+"");
}
public int getItemCount() {``
return mJobList.size();
}
public class JobHolder extends RecyclerView.ViewHolder{
ViewPager viewPager;
public JobHolder(View itemView) {
super(itemView);
viewPager=(ViewPager)itemView.findViewById(R.id.slidesPager);
}
}
main:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
JobAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView)findViewById(R.id.find_jobs_recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
List<String> list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
adapter = new JobAdapter(list,this);
mRecyclerView.setAdapter(adapter);
}
}
Very late answer but it might help some people...
Try using ViewPager2 ( an improved version of ViewPager) : https://developer.android.com/training/animation/screen-slide-2
In my case it solved the problem.