Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easy to use PagerAdapter for Views. Best used in combination with MVP module of Blade library (https://github.com/FrantisekGazo/Blade)
package eu.f3rog.ui.adapter;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Class {@link ViewPagerAdapter}
*
* @author FrantisekGazo
* @version 2016-02-27
*/
public final class ViewPagerAdapter
extends PagerAdapter {
public static final class Item {
@LayoutRes
public final int layout;
public final Object tagObject;
public Item(int layout, Object tagObject) {
this.layout = layout;
this.tagObject = tagObject;
}
}
public static final class Builder {
private final Context mContext;
private final List<Item> mItems;
public Builder(@NonNull Context context) {
mContext = context;
mItems = new ArrayList<>();
}
public Builder add(@LayoutRes int layoutRes, @NonNull Object tagObject) {
mItems.add(new Item(layoutRes, tagObject));
return this;
}
public MyPagerAdapter build() {
return new MyPagerAdapter(mContext, mItems);
}
}
private final LayoutInflater mInflater;
private final List<Item> mItems;
public MyPagerAdapter(@NonNull Context context, @NonNull List<Item> items) {
mInflater = LayoutInflater.from(context);
mItems = items;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mItems.get(position).tagObject.toString();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Item item = mItems.get(position);
View view = mInflater.inflate(item.layout, container, false);
container.addView(view);
view.setTag(item.tagObject);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment