SnapHelper Item Position - java

I'm using vertical RecyclerView to list my items and SnapHelper to snap center item. The idea is to randomize selection, so user swipe screen or shake the device and it is scrolling to random position.
Number of items is 20, however I use Integer.MAX_VALUE for the number of elements in RecyclerView and initialize RecyclerView with position Integer.MAX_VALUE / 2 to create some kind of endless list.
To scroll to random position on device shake I need to know current snapped item position.
Is there any way to do it?
Here is my Fragment code:
public class PlaceListFragment extends Fragment {
private static final String TAG = "PlaceListFragment";
public static final String ARG_KEY1 = "key1";
private ArrayList<PlaceItem> places;
private RecyclerView recyclerView;
private SensorManager sensorManager;
private float accelValue;
private float accelLast;
private float shake;
SnapHelper snapHelper;
Vibrator vibe;
public static PlaceListFragment newInstance() {
Bundle args = new Bundle();
PlaceListFragment fragment = new PlaceListFragment();
fragment.setArguments(args);
return fragment;
}
public static PlaceListFragment newInstance(ArrayList<PlaceItem> places) {
Bundle args = new Bundle();
args.putParcelableArrayList(PlaceListActivity.KEY_PLACES, places);
PlaceListFragment fragment = new PlaceListFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
places = getArguments().getParcelableArrayList(PlaceListActivity.KEY_PLACES);
accelValue = SensorManager.GRAVITY_EARTH;
accelLast = SensorManager.GRAVITY_EARTH;
shake = 0.00f;
vibe = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_place_list, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.place_list);
snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setOnFlingListener(snapHelper);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new PlaceListAdapter(getActivity(), places));
recyclerView.scrollToPosition(PlaceListAdapter.MIDDLE);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
return v;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
private final SensorEventListener sensorListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
accelLast = accelValue;
accelValue = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = accelValue - accelLast;
shake = shake * 0.9f + delta;
if (shake > 12) {
vibe.vibrate(200);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
And here is adapter:
public class PlaceListAdapter extends RecyclerView.Adapter<PlaceListAdapter.PlaceAdapterHolder> {
private final FragmentActivity context;
public static final int HALF_MAX_VALUE = Integer.MAX_VALUE/2;
public static int MIDDLE;
private List<PlaceItem> placeItems;
public static class PlaceAdapterHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView textMain;
private TextView textRating;
public PlaceAdapterHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.icon);
textMain = (TextView) itemView.findViewById(R.id.txt_main_line);
textRating = (TextView) itemView.findViewById(R.id.txt_right_field);
}
public void bindPlace(PlaceItem placeItem) {
String placeName = placeItem.getName() == null? "?":placeItem.getName();
String firstLetter = placeName.substring(0, 1);
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
int color = generator.getColor(placeName);
TextDrawable drawable = TextDrawable.builder()
.beginConfig()
.toUpperCase()
.endConfig()
.buildRect(firstLetter, color);
image.setImageDrawable(drawable);
textMain.setText(placeItem.getName());
textRating.setText(placeItem.getRating());
}
}
public PlaceListAdapter(FragmentActivity context, List<PlaceItem> placeItems) {
this.context = context;
this.placeItems = placeItems;
MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % placeItems.size();
}
#Override
public PlaceListAdapter.PlaceAdapterHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.place_list_one_line_item, parent, false);
return new PlaceAdapterHolder(view);
}
#Override
public int getItemCount() {
return Integer.MAX_VALUE;
}
#Override
public void onBindViewHolder(PlaceListAdapter.PlaceAdapterHolder holder, final int position) {
final PlaceItem placeItem = getItem(position);
holder.bindPlace(placeItem);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = context.getSupportFragmentManager();
PlaceDetailsFragment dialog = PlaceDetailsFragment.newInstance(getItem(position));
dialog.show(fm, "DETAILS_DIALOG");
}
});
}
private PlaceItem getItem(int position)
{
return placeItems.get(position % placeItems.size());
}
}

I used this on a project that had a RecyclerView with SnapHelper, not sure if it is what you want.
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new DemoSlidesAdapter(getApplicationContext());
mRecyclerView.setAdapter(mAdapter);
final SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == RecyclerView.SCROLL_STATE_IDLE) {
View centerView = snapHelper.findSnapView(mLayoutManager);
int pos = mLayoutManager.getPosition(centerView);
Log.e("Snapped Item Position:",""+pos);
}
}
});

I try to use this code with a PagerSnapHelper to mimic the pager behaviour and it was useful but i found some corner cases to solve, if you move fast from the last page to the first one and keep swapping until see the boundarie then the IDLE state doesnt happen and you lose your index. to solve that I move out the position from the IF and add a extra condition for this corner case.
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val centerView = snapHelper.findSnapView(mLayoutManager)
val pos = mLayoutManager.getPosition(centerView!!)
if (newState == RecyclerView.SCROLL_STATE_IDLE || (pos == 0 && newState == RecyclerView.SCROLL_STATE_DRAGGING)) {
Log.d("BINDING", "positionView SCROLL_STATE_IDLE: $pos")
}
}
Code is in kotlin hope it helps

private fun recyclerViewScrollListener() = object: RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// layoutManager is LinearLayoutManager
val pos = layoutManager.findFirstCompletelyVisibleItemPosition()
Log.e(TAG, "onScrollStateChanged: $pos")
}
}
}
recyclerView.setOnScrollListener(recyclerViewScrollListener())

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
....
}
})

Related

How to save scroll state of a Recyclerview when an item is clicked?

I have an issue with Recyclerview item selection , which is set up in a fragment , the problem is each page which is created by ViewVager has its own instance of the Recyclerview so the output is that selecting Recyclerview items will reset the scroll state of the Recyclerview, so I'm looking for a solution to to save scroll state of a Recyclerview when an item is clicked.
Fragment onViewCreated
// setting RecyclerView
mEpisodesList = (CustomRecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
int scrollValue = mEpisodesList.getHorizontalScrollOffset();
mCallback.sendText(pos, scrollValue);
}
});
mEpisodesList.setAdapter(planetAdapter);
int scrollValue = getArguments().getInt("scrollValue");
new Handler().postDelayed(() -> mEpisodesList.scrollBy(scrollValue, 0), 100);
activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked {
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId, Integer.parseInt(mEpisodes.get(i).getSeason()), Integer.parseInt(mEpisodes.get(i).getEpisode()), i, mScrollValue));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i = 0; i < episodeslist.size(); i++) {
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
// return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
return fragments.get(index);
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
Recyclerview adapter
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
public interface OnItemClickListener {
void onItemClick(int item);
}
private final ArrayList<PlanetModel> episodeslist;
private final OnItemClickListener listener;
SharedPreferences getPref = getContext().getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
int pos = getPref.getInt("i", 0);
int isPlanetSelected = pos;
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition;
}
#NonNull
#Override
public PlanetAdapter.PlanetViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.planet_row, parent, false);
return new PlanetViewHolder(v);
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
}
//holder.image.setImageResource(R.drawable.planetimage);
//vh.text.setText(episodeslist.get(position).toString());
}
#Override
public int getItemCount() {
return episodeslist.size();
}
public class PlanetViewHolder extends RecyclerView.ViewHolder {
protected TextView text;
public PlanetViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text_id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG_TAG", "onClick: current item: " + highlightedPos);
final int previousItem = isPlanetSelected;
isPlanetSelected = getPosition();
SharedPreferences setPref = v.getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
setPref.edit().putInt("newPosition", getPosition()).apply();
listener.onItemClick(getPosition());
}
});
}
// public void bind(final PlanetModel item, final OnItemClickListener listener) {
// }
}
You can solve this by tracking the current scroll value of the RecyclerView, and whenever you hit an a ReyclerView item; add a new parameter to the listener callback with this tracked scroll value to update the new fragment that will be shown on the ViewPager.
Track the scroll value:
mEpisodesList.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
scrollValue += dx;
}
});
Pass it as interface callback:
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos, scrollValue);
}
});
And update that in the list of ViewPager fragments before scrolling to the new page:
#Override
public void sendText(int position, int scrollValue) {
mScrollValue = scrollValue;
TvShowEpisodeDetailsFragment frag = fragments.get(position);
Bundle arguments = frag.getArguments();
arguments.putInt("scrollValue", scrollValue);
mViewPager.setCurrentItem(position, false);
}
try this
// save
recyclerViewState = binding.mainList.layoutManager?.onSaveInstanceState()
// restore
recyclerViewState?.let {
binding.mainList.layoutManager?.onRestoreInstanceState(it)
}

How to load AdMobs inside RecycleView after every 5th row?

I am trying to implement AdMobs to load ads, every 5th row but i am having a difficult time, as you can see from my screenshot ads are being loaded successfully but they're being loaded after every row. Can someone help me accomplish this? I already tried reading through post on stack overflow but none seems to help. Thank you in advance. image screenshot
Fragment
public class SectorPerformanceFragment extends Fragment {
private RecyclerView newsFeedRecycleView;
private SectorPerformanceAdapter mostActiveAdapter;
private RecyclerViewAdopter recyclerViewAdopter;
public static final int ITEMS_PER_AD = 9;
private RecyclerView.LayoutManager layoutManager;
private RequestQueue requestQueue;
private JSONObject stockDetails;
public static ArrayList<SectorPerformanceModel> mostActiveArrayList;
private RequestQueue requestQueues;
private ImageView backImage;
private View rootView;
private ProgressBar loadingProgressBar;
private TextView sectorNameTv;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.recycle_view_list_ui, container, false);
sectorNameTv = rootView.findViewById(R.id.sectorNameTv);
sectorNameTv.setText("Sector Performance");
loadingProgressBar = rootView.findViewById(R.id.loadingProgressBar);
backImage = rootView.findViewById(R.id.backImageView);
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
//
// Fragment generalMarketFragment = new BrowseFragment();
// FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// fragmentTransaction.replace(R.id.fragment_container, generalMarketFragment);
// fragmentTransaction.addToBackStack(null);
// fragmentTransaction.commit();
}
});
requestQueues = Volley.newRequestQueue(getActivity());
findViewById();
mostActiveArrayList = new ArrayList<>();
initRecycleView();
retreiveBundleInformation();
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void findViewById() {
newsFeedRecycleView = rootView.findViewById(R.id.recylcle_view_list);
}
//set up RecycleVIew/listener to detect taps layout manager tels recycle view how to display the list.. without it, nothing shows up
public void initRecycleView() {
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
newsFeedRecycleView.setHasFixedSize(true);
newsFeedRecycleView.setLayoutManager(layoutManager);
//mostActiveAdapter = new SectorPerformanceAdapter(getContext(), mostActiveArrayList);
// recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//
// //newsFeedRecycleView.setAdapter(mostActiveAdapter);
// newsFeedRecycleView.setAdapter(recyclerViewAdopter);
}
//download news data stocknewsapi..
private void downloadStockList(String api) {
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
api,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
loadingProgressBar.setVisibility(View.INVISIBLE);
//Log.i("jsonResponse", response.toString());
// Process the JSON
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
// Get current json object
try {
stockDetails = response.getJSONObject(i);
Log.i("stockDetails", stockDetails.toString());
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//newsFeedRecycleView.setAdapter(mostActiveAdapter);
newsFeedRecycleView.setAdapter(recyclerViewAdopter);
//recyclerViewAdopter.notifyDataSetChanged();
// mostActiveArrayList.add(sectorPerformanceModel);
// mostActiveAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueues.add(jsonArrayRequest);
}
public void retreiveBundleInformation() {
downloadStockList("APIKEY");
}
}
Adapter
[public class RecyclerViewAdopter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private List<SectorPerformanceModel> mList;
public RecyclerViewAdopter(Context mContext, List<SectorPerformanceModel> mList) {
this.mList = mList;
this.mContext = mContext;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
private TextView newsTitle, sourceName, epsEstiatmate;
private CircleImageView newsThumbImage;
public MyViewHolder(View view) {
super(view);
epsEstiatmate = itemView.findViewById(R.id.formTypeTv);
newsTitle = itemView.findViewById(R.id.tickerTv);
sourceName = itemView.findViewById(R.id.dateTv);
newsThumbImage= itemView.findViewById(R.id.defaultImageColor);
newsThumbImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("tapped","TAPPED");
}
});
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public AdView mAdView;
public ViewHolderAdMob(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch(viewType){
case 1:{
View v = inflater.inflate(R.layout.trending_stock_row, parent, false);
viewHolder = new MyViewHolder(v);
break;
}
case 2:{
View v = inflater.inflate(R.layout.ads_row, parent, false);
viewHolder = new ViewHolderAdMob(v);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
SectorPerformanceModel model= mList.get(holder.getAdapterPosition());
switch(holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
Random r = new Random();
int red = r.nextInt(255 - 0 + 1) + 0;
int green = r.nextInt(255 - 0 + 1) + 0;
int blue = r.nextInt(255 - 0 + 1) + 0;
GradientDrawable draw = new GradientDrawable();
draw.setShape(GradientDrawable.OVAL);
draw.setColor(Color.rgb(red, green, blue));
viewHolder.newsThumbImage.setBackground(draw);
viewHolder.newsTitle.setText(model.getSector());
viewHolder.sourceName.setText(model.getChangesPercentage());
break;
}
case 2:{
break;
}
}
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getViewType();
}
#Override
public int getItemCount() {
return mList.size();
}
}][1]
It looks like you are adding 2 items to your adapter's data source for each element in your API response: one element has viewType 1 and the other viewType 2:
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
Your adapter is rendering items with viewType 2 as ad rows, so if you want to display an ad row every 5 rows you'll need to update the downloadStockList method to execute this
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
only after having added 4 items with viewType 1.

Context must not be null

I get this error in the LogCat when I try to run the application.
java.lang.IllegalArgumentException: Context must not be null.
This happens when I add the Picasso code in the class.
here is the adpater.Java
It says the Context is null, I have read other posts but I could not find a solution.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private List<App> mApps;
private boolean mHorizontal;
private boolean mPager;
private Context mContext;
public Adapter(Context ctx, boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
this.mContext=ctx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mPager) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adaper_pager, parent, false));
} else {
return mHorizontal ? new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter, parent, false)) :
new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_vertical, parent, false));
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
App app = mApps.get(position);
//holder.imageView.setImageResource(app.getDrawable());
Picasso.with(mContext).load(app.getLink()).into(holder.imageView);
holder.nameTextView.setText(app.getName());
holder.ratingTextView.setText(String.valueOf(app.getRating()));
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return mApps.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView nameTextView;
public TextView ratingTextView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.igOne);
nameTextView = (TextView) itemView.findViewById(R.id.nameTV);
ratingTextView = (TextView) itemView.findViewById(R.id.rate);
}
}
}
Please Help. some say it is because the imageView is null. I have no idea about that.
MainActivity
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
private Context mContext = MainActivity.this;
private static final int ACTIVITY_NUM = 0;
public static final String ORIENTATION = "orientation";
private RecyclerView mRecyclerView;
private boolean mHorizontal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "OnCreate: Starting MainActivity");
setupBottomNavigationView();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
if (savedInstanceState == null) {
mHorizontal = true;
} else {
mHorizontal = savedInstanceState.getBoolean(ORIENTATION);
}
setupAdapter();
}
/**
* Setup Bottom Navigation View
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: Setting up Bottom Navigation View");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottom_nav_bar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
public void click(View v) {
Intent mIntent = null;
switch (v.getId()) {
case R.id.serve:
mIntent = new Intent(this, SearchActivity.class);
break;
case R.id.imageButton2:
mIntent = new Intent(this, SearchActivity.class);
break;
}
startActivity(mIntent);
}
///////////
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(ORIENTATION, mHorizontal);
}
private void setupAdapter() {
List<App> apps = getApps();
SnapAdapter snapAdapter = new SnapAdapter();
if (mHorizontal) {
snapAdapter.addSnap(new Snap(Gravity.CENTER_HORIZONTAL, "Snap Start", apps));
snapAdapter.addSnap(new Snap(Gravity.START, "Snap Middle", apps));
snapAdapter.addSnap(new Snap(Gravity.END, "Snap End", apps));
snapAdapter.addSnap(new Snap(Gravity.CENTER, "Pager snap", apps));
} else {
snapAdapter.addSnap(new Snap(Gravity.CENTER_VERTICAL, "Snap center", apps));
snapAdapter.addSnap(new Snap(Gravity.TOP, "Snap top", apps));
snapAdapter.addSnap(new Snap(Gravity.BOTTOM, "Snap bottom", apps));
}
mRecyclerView.setAdapter(snapAdapter);
}
private List<App> getApps() {
List<App> apps = new ArrayList<>();
apps.add(new App("Google+", "http://uupload.ir/files/aud7_brickone.jpg", 4.6f));
return apps;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
}
SnapAdapter
public class SnapAdapter extends RecyclerView.Adapter<SnapAdapter.ViewHolder> implements GravitySnapHelper.SnapListener {
public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;
private Context mContext;
private ArrayList<Snap> mSnaps;
// Disable touch detection for parent recyclerView if we use vertical nested recyclerViews
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
};
public SnapAdapter() {
mSnaps = new ArrayList<>();
}
public void addSnap(Snap snap) {
mSnaps.add(snap);
}
#Override
public int getItemViewType(int position) {
Snap snap = mSnaps.get(position);
switch (snap.getGravity()) {
case Gravity.CENTER_VERTICAL:
return VERTICAL;
case Gravity.CENTER_HORIZONTAL:
return HORIZONTAL;
case Gravity.START:
return HORIZONTAL;
case Gravity.TOP:
return VERTICAL;
case Gravity.END:
return HORIZONTAL;
case Gravity.BOTTOM:
return VERTICAL;
}
return HORIZONTAL;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = viewType == VERTICAL ? LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_snap_vertical, parent, false)
: LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_snap, parent, false);
if (viewType == VERTICAL) {
view.findViewById(R.id.recycle_view).setOnTouchListener(mTouchListener);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Snap snap = mSnaps.get(position);
holder.snapTextView.setText(snap.getText());
if (snap.getGravity() == Gravity.START || snap.getGravity() == Gravity.END) {
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
new GravitySnapHelper(snap.getGravity(), false, this).attachToRecyclerView(holder.recyclerView);
} else if (snap.getGravity() == Gravity.CENTER_HORIZONTAL) {
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), snap.getGravity() == Gravity.CENTER_HORIZONTAL ?
LinearLayoutManager.HORIZONTAL : LinearLayoutManager.VERTICAL, false));
holder.recyclerView.setOnFlingListener(null);
new LinearSnapHelper().attachToRecyclerView(holder.recyclerView);
} else if (snap.getGravity() == Gravity.CENTER) { // Pager snap
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
new PagerSnapHelper().attachToRecyclerView(holder.recyclerView);
} else { // Top / Bottom
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext()));
holder.recyclerView.setOnFlingListener(null);
new GravitySnapHelper(snap.getGravity()).attachToRecyclerView(holder.recyclerView);
}
holder.recyclerView.setAdapter(new Adapter(mContext, snap.getGravity() == Gravity.START
|| snap.getGravity() == Gravity.END
|| snap.getGravity() == Gravity.CENTER_HORIZONTAL,
snap.getGravity() == Gravity.CENTER, snap.getApps()));
}
#Override
public int getItemCount() {
return mSnaps.size();
}
#Override
public void onSnap(int position) {
Log.d("Snapped: ", position + "");
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView snapTextView;
public RecyclerView recyclerView;
public ViewHolder(View itemView) {
super(itemView);
snapTextView = (TextView) itemView.findViewById(R.id.snapTextView);
recyclerView = (RecyclerView) itemView.findViewById(R.id.recycle_view);
}
}
}
java.lang.IllegalArgumentException: Context must not be null.
A constructor in Java is a block of code similar to a method that's
called when an instance of an object is created.
You should pass Context
private Context mContext;
public Adapter(Context ctx,boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
this.mContext=ctx; // Call here
}
Logcat Throws
the error is: Error:(110, 40) error: constructor Adapter in class
Adapter cannot be applied to given types; required:
boolean,boolean,List,Context found: boolean,boolean,List
reason: actual and formal argument lists differ in length
Pass Value LIKE
new Adapter(Your_Activity.this, boolean, boolean , List<App>);
Call Adapter like this
Adapter mAdapter = new Adapter (Youractivity_name.this, boolean, boolean , list);
and change the constructor to
public Adapter(Context context ,boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
mContext = context;
}

change the position of two view (Text view ) using Drag And Drop functionality

i want change the position of Text View using drag and drop functionally in android using Drag listener and animation. i am done a design using following code. i want to change the order of text view using Drag Listener. thanks i give a image of design and i want change position of text view using drag and drop
public void loadtable()
{
Sorting_Linear = (LinearLayout) findViewById(R.id.Sorting_Linear);
submit = (Button) findViewById(R.id.submit);
LinearLayout[] llRow = new LinearLayout[5];
final TextView[] outletnametxt = new TextView[5];
final ImageView[] imageButtonup = new ImageView[5];
final ImageView[] imageButtondown = new ImageView[5];
final LinearLayout[] Linearlayout = new LinearLayout[5];
for (int i = 0; i < 5; i++) {
llRow[i] = new LinearLayout(mContext);
LinearLayout.LayoutParams paramsllRow = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
paramsllRow.setMargins(0, 2, 0, 0);
llRow[i].setLayoutParams(paramsllRow);
llRow[i].setOrientation(LinearLayout.HORIZONTAL);
outletnametxt[i] = new TextView(mContext);
outletnametxt[i].setLayoutParams(nametxt);
outletnametxt[i].setText(olm_name[i]);
outletnametxt[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
outletnametxt[i].setTextSize(20);
outletnametxt[i].setGravity(Gravity.CENTER);
outletnametxt[i].setBackgroundColor(mContext.getResources().getColor(android.R.color.white));
llRow[i].addView(outletnametxt[i]);
imageButtonup[i] = new ImageView(mContext);
imageButtonup[i].setLayoutParams(imagebtnup);
imageButtonup[i].setImageResource(R.drawable.arrowup);
imageButtondown[i] = new ImageView(mContext);
imageButtondown[i].setLayoutParams(imagebtndown);
imageButtondown[i].setImageResource(R.drawable.arrowdown);
Linearlayout[i] = new LinearLayout(mContext);
Linearlayout[i].setLayoutParams(linearlayout);
Linearlayout[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
Linearlayout[i].setBackgroundColor(mContext.getResources().getColor(android.R.color.white));
Linearlayout[i].setOrientation(LinearLayout.VERTICAL);
Linearlayout[i].addView(imageButtonup[i]);
Linearlayout[i].addView(imageButtondown[i]);
llRow[i].addView(Linearlayout[i]);
Sorting_Linear.addView(llRow[i]);
}
Create below interface ItemTouchHelperAdapter
public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);}
Create second interface ItemTouchHelperViewHolder
public interface ItemTouchHelperViewHolder {
void onItemSelected();
void onItemClear();}
Create OnStartDragListener
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);}
Create below class
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
public static final float ALPHA_FULL = 1.0f;
private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return true;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// Set movement flags based on the layout manager
if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
final int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
} else {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
if (source.getItemViewType() != target.getItemViewType()) {
return false;
}
// Notify the adapter of the move
mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
// Notify the adapter of the dismissal
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
#Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Fade out the view as it is swiped out of the parent's bounds
final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
} else {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
#Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
// We only want the active item to change
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder instanceof ItemTouchHelperViewHolder) {
// Let the view holder know that this item is being moved or dragged
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemSelected();
}
}
super.onSelectedChanged(viewHolder, actionState);
}
#Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setAlpha(ALPHA_FULL);
if (viewHolder instanceof ItemTouchHelperViewHolder) {
// Tell the view holder it's time to restore the idle state
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemClear();
}
}}
Now just add this code to your recycler view adapter
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecyclerListAdapter(Activity_OutletSorting.this, onStartDragListener, olm_name,idopeningclosing);
recyclerView.setAdapter(adapter);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);

Get NullPointerException in LinearLayoutManager

I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
Here is the RecyclerFragment:
public class ThreeFragment extends Fragment{
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
private DataAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
private List<Student> studentList;
protected Handler handler;
public ThreeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_one, container, false);
tvEmptyView = (TextView) rootview.findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
studentList = new ArrayList<Student>();
handler = new Handler();
loadData();
// 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);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new DataAdapter(studentList, mRecyclerView);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
// mAdapter.notifyDataSetChanged();
if (studentList.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
studentList.add(null);
mAdapter.notifyItemInserted(studentList.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
studentList.remove(studentList.size() - 1);
mAdapter.notifyItemRemoved(studentList.size());
//add items one by one
int start = studentList.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
studentList.add(new Student("Student " + i, "AndroidStudent" + i + "#gmail.com"));
mAdapter.notifyItemInserted(studentList.size());
}
mAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 2000);
}
});
return rootview;
}
// load initial data
private void loadData() {
for (int i = 1; i <= 20; i++) {
studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
}
Here is the adapter:
public class DataAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<Student> studentList;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public DataAdapter(List<Student> students, RecyclerView recyclerView) {
studentList = students;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager mLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = mLayoutManager.getItemCount();
lastVisibleItem = mLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return studentList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_row, parent, false);
vh = new StudentViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof StudentViewHolder) {
Student singleStudent = (Student) studentList.get(position);
((StudentViewHolder) holder).tvName.setText(singleStudent.getName());
((StudentViewHolder) holder).tvEmailId.setText(singleStudent.getEmailId());
((StudentViewHolder) holder).student = singleStudent;
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return studentList.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
//
public static class StudentViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public Student student;
public StudentViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
tvEmailId = (TextView) v.findViewById(R.id.tvEmailId);
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),
"OnClick :" + student.getName() + " \n " + student.getEmailId(),
Toast.LENGTH_SHORT).show();
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
}
}
}

Categories

Resources