PagerAdapter don't attach to ViewPager - android

I have follow view structure:
<RecyclerView>
<CardView>
<RecyclerView id:="inner_recycler">
</RecyclerView>
</CardView>
<CardView>
<ViewPager id:="pager_1">
</ViewPager>
</CardView>
<CardView>
<ViewPager id:="pager_2">
</ViewPager>
</CardView>
<CardView>
<ViewPager id:="pager_3">
</ViewPager>
</CardView>
</RecyclerView>
RecyclerView adapter:
public class TodayStatsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Map<Date, StatsBean> mStats;
private Context mContext;
public TodayStatsAdapter(Context context, Map<Date, StatsBean> stats) {
mStats = stats;
mContext = context;
}
#Override
public int getItemViewType(int position) {
if (position > 0) {
return R.layout.today_stats_other_item;
} else {
return R.layout.today_stats_first_item;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
if (R.layout.today_stats_first_item == viewType) {
return new TodayFirstStatsHolder(view);
} else {
return new TodayOtherStatsHolder(view, mContext);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
List<Date> listDate = new ArrayList<>(mStats.keySet());
Collections.sort(listDate, Date::compareTo);
if (holder instanceof TodayFirstStatsHolder) {
TodayFirstStatsHolder viewHolder = (TodayFirstStatsHolder) holder;
final Date lastDate = listDate.get(listDate.size() - 1);
final StatsBean bean = mStats.get(lastDate);
viewHolder.setDateTime(mContext.getString(R.string.stats_today_text)+ " " + lastDate.getHours() + ":" + lastDate.getMinutes());
viewHolder.initRecycler(bean);
}
if (holder instanceof TodayOtherStatsHolder) {
TodayOtherStatsHolder viewHolder = (TodayOtherStatsHolder) holder;
final Date lastDate = listDate.get(position - 1);
final StatsBean bean = mStats.get(lastDate);
viewHolder.setDateTime(mContext.getString(R.string.stats_today_text)+ " " + lastDate.getHours() + ":" + lastDate.getMinutes());
viewHolder.initPager(bean);
}
}
#Override
public int getItemCount() {
return mStats.size();
}
public static class TodayFirstStatsHolder extends RecyclerView.ViewHolder {
private TextView mItemDateText;
private RecyclerView mItemRecyclerView;
private Context mContext;
public TodayFirstStatsHolder(#NonNull View itemView) {
super(itemView);
mContext = itemView.getContext();
mItemDateText = itemView.findViewById(R.id.first_item_date_text);
mItemRecyclerView = itemView.findViewById(R.id.first_item_recycler_view);
}
public void setDateTime(String dateTime) {
mItemDateText.setText(dateTime);
}
public void initRecycler(StatsBean bean) {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext) {
#Override
public boolean canScrollVertically() {
return false;
}
};
mItemRecyclerView.setLayoutManager(layoutManager);
mItemRecyclerView.setHasFixedSize(true);
TodayStatsFirstItemAdapter adapter = new TodayStatsFirstItemAdapter(bean, mContext);
mItemRecyclerView.setAdapter(adapter);
}
}
public static class TodayOtherStatsHolder extends RecyclerView.ViewHolder {
private TextView mItemDateText;
private ViewPager mItemViewPager;
private Context mContext;
public TodayOtherStatsHolder(#NonNull View itemView, Context context) {
super(itemView);
mContext = context;
mItemDateText = itemView.findViewById(R.id.first_item_date_text);
mItemViewPager = itemView.findViewById(R.id.other_item_pager);
mItemViewPager.setVisibility(View.VISIBLE);
}
public void setDateTime(String dateTime) {
mItemDateText.setText(dateTime);
}
public void initPager(StatsBean bean) {
TodayStatsOtherItemPagerAdapter pagerAdapter = new TodayStatsOtherItemPagerAdapter(
((MainActivity) mContext).getSupportFragmentManager(),
bean.getStats()
);
mItemViewPager.setAdapter(pagerAdapter);
}
}
}
PagerAdapter:
public class TodayStatsOtherItemPagerAdapter extends FragmentStatePagerAdapter {
private final List<Map.Entry<String, Integer>> mEntriesStats;
public TodayStatsOtherItemPagerAdapter(FragmentManager fm, Map<String, Integer> stats) {
super(fm);
mEntriesStats = new ArrayList<>(stats.entrySet());
}
#Override
public Fragment getItem(int position) {
return TodayStatsPagerFragment.newInstance(mEntriesStats.get(position));
}
#Override
public int getCount() {
return mEntriesStats.size();
}
}
The first RecyclerView has an adapter which creating CardView with a RecyclerView or a ViewPager. The inner RecyclerView is initializing and working normally. Every ViewPagers have own PagerAdapters and ViewHolders. The "pager_1" is creating and inflating normally but other pagers don't attached own adapters and therefore don't show information. Why did adapters demonstrate such behavior? How to do that every ViewPager will attach own adapter?
Sorry for my bad English. I hope you will help me.

Related

NestedRecyclerView Problem - Last item of the second RecyclerView is duplicated into the first one after the keyboard appears

I'm desperate.
I have a nested recycler view. Each outer element has an array of inner elements. A different adapter has been created for the inner elements. I am creating an array of external elements of class "KairosWithEvents", each of which contains internal elements of class "Event". Everything is displayed well. When elements are added, everything is also updated. For testing, I created two objects of the "KairosWithEvent" class. In the first object I have placed two objects of the "Event" class, and in the second - three objects. But when I want to change the EditText value, the keyboard appears. And the last element of the second object appears in the first object. How can I fix it? Objects are not moved or duplicated, but showed incorrectly.
This is what a nestled recycler view looks like initially.
And this is what a nested recycler view looks like after the keyboard appears. The "Эвент5" element is duplicated to the first element for some reason.
Here's my code: Outer Adapter:
public class EventAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static List<Item> items;
private static RecyclerViewClickInterface listener;
private RecyclerView.RecycledViewPool sharedPool = new RecyclerView.RecycledViewPool();
private Context context;
public EventAdapter() {
items = new ArrayList<>();
this.context = context;
}
public EventAdapter(List<Item> newItems){
items = newItems;
}
class KairosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private TextView title;
private CheckBox iv;
private RecyclerView rv;
public KairosViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv);
iv = itemView.findViewById(R.id.iv);
rv = itemView.findViewById(R.id.rvSteaks);
itemView.setBackgroundColor(Color.parseColor("#91b3f2"));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void bind(KairosWithEvents kairosWithEvents){
title.setText(kairosWithEvents.kairos.kairosId + " = " + kairosWithEvents.kairos.title);
LinearLayoutManager layoutManager = new LinearLayoutManager(
rv.getContext(),
LinearLayoutManager.VERTICAL,
false);
List<Item> itemsEvents = new ArrayList<>();
kairosWithEvents.events.forEach(i -> itemsEvents.add(new Item(Constants.EVENT_KAIROS, i)));
SubAdapter childAdapter = new SubAdapter(itemsEvents);
rv.setLayoutManager(layoutManager);
rv.setAdapter(childAdapter);
rv.setRecycledViewPool(sharedPool);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION){
listener.onItemKairosWithEvents( ((KairosWithEvents) items.get(position).object) );
}
}
#Override
public boolean onLongClick(View view) {
return false;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType){
case Constants.KAIROS:
return new KairosViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_ex, parent, false));
}
return null;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)){
case Constants.KAIROS:
KairosWithEvents kairos = ((KairosWithEvents) items.get(position).object);
((KairosViewHolder) holder).bind(kairos);
break;
}
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public int getItemViewType(int position) {
return items.get(position).type;
}
}
Inner Adapter:
public class SubAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static List<Item> items;
public SubAdapter(List<Item> newItems) {
items = newItems;
}
static class EventViewHolder extends RecyclerView.ViewHolder {
private TextView title;
public EventViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv);
itemView.setBackgroundColor(Color.parseColor("#ffc8a8"));
}
void bind(Event event){
title.setText(event.eventId + " = " + event.title);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case Constants.EVENT_KAIROS:
return new EventViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_sub, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)){
case Constants.EVENT_KAIROS:
Event event = (Event) items.get(position).object;
((EventViewHolder) holder).bind(event);
break;
}
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public int getItemViewType(int position) {
return items.get(position).type;
}
}
In SubAdapter, remove the static keyword from your items field:
private static List<Item> items;
Should be this instead:
private List<Item> items;
You should make the same change to your outer adapter, but since there's only one of them at a time it doesn't wind up causing issues.

Sorting items in RecyclerView Android

I've a RecyclerView populated by an ArrayList of custom objects. I've implemented Comparable interface to sort items in array list based on index. Sorting gives me the desired results but when i populate RecyclerView, my items appear in the order they were in before sorting.
I'm calling Collection.sort(arrayList) in the constructor of Adaper like this:
public MyRecyclerViewListAdapter(List<Something> somethings, OnStartDragListener mDragStartListener) {
this.mDragStartListener = mDragStartListener;
this.somethings = somethings;
Collections.sort(this.somethings);
}
Even I sorted the list before sending it in as an argument to the constructor:
Collections.sort(this.somethings);
myRecyclerViewListAdapter = new myRecyclerViewListAdapter(somethings, this);
My Adapter code:
public class DefaultCurrenciesAdapter extends RecyclerView.Adapter<DefaultCurrenciesAdapter.MyViewHolder> implements ItemTouchHelperAdapter{
private List<Currency> currencies;
DataManager dataManager = new DataManager();
private OnStartDragListener mDragStartListener;
public DefaultCurrenciesAdapter(List<Currency> currencies, OnStartDragListener mDragStartListener) {
this.mDragStartListener = mDragStartListener;
this.currencies = currencies;
Collections.sort(this.currencies);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View currencyView = inflater.inflate(R.layout.currency_list,parent,false);
MyViewHolder viewHolder = new MyViewHolder(currencyView);
return viewHolder;
}
//populate data
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Currency currency = currencies.get(position);
TextView tvCurrencyValue = holder.tvCurrencyValue;
TextView tvCurrencyName=holder.tvCurrencyName;
tvCurrencyName.setText(currencies.get(position).getCode() + " - " + currencies.get(position).getName());
TextView tvUnitValue = holder.tvUnitValue;
tvUnitValue.setText("1 " + currencies.get(position).getCode()+ " = " +Double.toString(round(currencies.get(position).getRate()/ Currency.getBaseCurrencyRate(),2)) +" "+ Currency.getBaseCurrencyCode());
holder.ivFlag.setImageResource(App.getmContext().getResources().getIdentifier("drawable/"+currencies.get(position).getCountryCode().toLowerCase(),null,App.getmContext().getPackageName()));
}
#Override
public int getItemCount() {
return currencies.size();
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Collections.swap(currencies, fromPosition, toPosition);
int tempSort = currencies.get(fromPosition).getSortOrder();
dataManager.setSortOrder(currencies.get(fromPosition).getCode(), currencies.get(toPosition).getSortOrder());
dataManager.setSortOrder(currencies.get(toPosition).getCode(), tempSort);
notifyItemMoved(fromPosition, toPosition);
return true;
}
#Override
public void onItemDismiss(int position) {
dataManager.removeDefaultCurrency(currencies.get(position).getCode());
currencies.remove(position);
notifyItemRemoved(position);
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder,View.OnClickListener{
public TextView tvCurrencyValue;
public TextView tvCurrencyDecimals;
public TextView tvCurrencyName;
public TextView tvUnitValue;
public ImageView ivFlag;
public MyViewHolder(View itemView) {
super(itemView);
tvCurrencyValue = (TextView) itemView.findViewById(R.id.tvCurrencyValue);
tvCurrencyDecimals = (TextView) itemView.findViewById(R.id.tvCurrencyValueDecimals);
tvCurrencyName = (TextView)itemView.findViewById(R.id.tvCurrencyExp);
tvUnitValue = (TextView)itemView.findViewById(R.id.tvUnitValue);
ivFlag = (ImageView)itemView.findViewById(R.id.ivFlag);
Typeface fontMontserratSemiBold = Typeface.createFromAsset(App.getmContext().getAssets(), "fonts/Montserrat-SemiBold.otf");
Typeface fontMontserratRegular = Typeface.createFromAsset(App.getmContext().getAssets(), "fonts/Montserrat-Regular.otf");
tvCurrencyValue.setTypeface(fontMontserratSemiBold);
tvCurrencyDecimals.setTypeface(fontMontserratSemiBold);
tvCurrencyName.setTypeface(fontMontserratRegular);
tvUnitValue.setTypeface(fontMontserratRegular);
}
#Override
public void onItemSelected() {
}
#Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
#Override
public void onClick(View view) {
}
}
}
`

Sticky Header RecyclerView with multiple ArrayLists

I am implementing sticky header with RecyclerView. I have three sections (i.e 3 sticky headers) and they are working fine.Now I have taken three arraylists inside each section, I have initialized these list in my adapter and I am trying to get data of these lists on basis of header id inside onBindViewHolder. But it is not giving me the full list,just one string from each list (i.e under first section--data on first position of mylist,,,under second section-- data on second position of mylist1 ---under third section-- data on third position of mylist2)
Please Help !!
Code in Context:
StickyTestAdapter
public class StickyTestAdapter extends RecyclerView.Adapter<StickyTestAdapter.ViewHolder> implements
StickyHeaderAdapter<StickyTestAdapter.HeaderHolder> {
private Context mContext;
private ArrayList<String> mylist;
private ArrayList<String> mylist1;
private ArrayList<String> mylist2;
private static int countposition;
private String HEADER_FIRIST="HEADER_FIRIST";
private String HEADER_SECOND="HEADER_SECOND";
private String HEADER_THIRD="HEADER_THIRD";
public StickyTestAdapter(Context context) {
prepareData();
prepareData1();
prepareData2();
this.mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.item_test, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
long rowType= getHeaderId(position);
Log.e("getHeaderId----",""+rowType);
if (rowType==0){
if(!mylist.equals(""))
{
Log.e("list_data----", "" + mylist.get(position));
viewHolder.item.setText(mylist.get(position));
}
else
{
Log.e("Error--0--", "" + "error");
}
} else if (rowType==1){
if(!mylist1.equals(""))
{
Log.e("list_data1----", "" + mylist1.get(position));
viewHolder.item.setText(mylist1.get(position));
}
else
{
Log.e("Error---1-", "" + "error");
}
} else if (rowType==2){
if(!mylist2.equals(""))
{
Log.e("list_data2----", "" + mylist2.get(position));
viewHolder.item.setText(mylist2.get(position));
}
else
{
Log.e("Error----2", "" + "error");
}
}
}
#Override
public int getItemCount() {
if (getHeaderId(countposition)==0){
Log.e("mylist",""+mylist.size());
return mylist.size();
}else if (getHeaderId(countposition)==1){
Log.e("mylist1",""+mylist1.size());
return mylist1.size();
}else if (getHeaderId(countposition)==2){
Log.e("mylist2",""+mylist2.size());
return mylist2.size();
}
return 0;
}
#Override
public long getHeaderId(int pos) {
return pos;
}
#Override
public HeaderHolder onCreateHeaderViewHolder(ViewGroup parent) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.header_test, parent, false);
return new HeaderHolder(view);
}
#Override
public void onBindHeaderViewHolder(HeaderHolder viewholder, int count) {
countposition=count;
if (getItemViewType(count)==0){
viewholder.headertext.setText(HEADER_FIRIST);
}else if (getItemViewType(count)==1){
viewholder.headertext.setText(HEADER_SECOND);
}else if (getItemViewType(count)==2){
viewholder.headertext.setText(HEADER_THIRD);
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
item = (TextView)itemView.findViewById(R.id.text_item);
}
}
static class HeaderHolder extends RecyclerView.ViewHolder {
public TextView headertext;
public HeaderHolder(View itemView) {
super(itemView);
headertext = (TextView)itemView.findViewById(R.id.header_text);
}
}
#Override
public int getItemViewType(int position) {
return position;
}
public void prepareData()
{
mylist=new ArrayList<>();
mylist.add("rajendra");
mylist.add("rani");
mylist.add("rahul");
}
public void prepareData1()
{
mylist1=new ArrayList<>();
mylist1.add("ravi");
mylist1.add("vikram");
mylist1.add("rakesh");
}
public void prepareData2()
{
mylist2=new ArrayList<>();
mylist2.add("apple");
mylist2.add("ashok");
mylist2.add("vikash");
}
}
Question is quite old. But that code looks complicated to read, personally I try to not reinvent what others did quite well by creating libraries.
GitHub is full of source that you can import. Some examples: FlexibleAdapter, FastAdapter, Epoxy and others.
I have build the first one, but you can try the others as well.
With mine, having multiple views and headers with sections is quite easy, I point here the wiki page where I define the section and how to initialize it.
Along with this feature, you have a lot more functionalities that makes your life easier.
I divide arraylist into 3 section based on alphabet like contactlist.
For that i use SectionedRecyclerViewAdapter
MainActivity.java
public class MainActivity extends AppCompactActivity {
private SectionedRecyclerViewAdapter sectionAdapter;
#Override
public View onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
sectionAdapter = new SectionedRecyclerViewAdapter();
for(char alphabet = 'a'; alphabet <= 'z';alphabet++) {
List<String> contacts = getContactsWithLetter(alphabet);
if (contacts.size() > 0) {
sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
return view;
}
#Override
public void onResume() {
super.onResume();
if (getActivity() instanceof AppCompatActivity) {
AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity.getSupportActionBar() != null)
activity.getSupportActionBar().setTitle(R.string.nav_example1);
}
}
private List<String> getContactsWithLetter(char letter) {
List<String> contacts = new ArrayList<>();
for (String contact : getResources().getStringArray(R.array.names_)) {
if (contact.charAt(0) == letter) {
contacts.add(contact);
}
}
return contacts;
}
private class ContactsSection extends StatelessSection {
String title;
List<String> list;
ContactsSection(String title, List<String> list) {
super(new SectionParameters.Builder(R.layout.section_ex1_item)
.headerResourceId(R.layout.section_ex1_header)
.build());
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size();
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return new ItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
String name = list.get(position);
itemHolder.tvItem.setText(name);
itemHolder.imgItem.setImageResource(name.hashCode() % 2 == 0 ? R.drawable.ic_face_black_48dp : R.drawable.ic_tag_faces_black_48dp);
itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), String.format("Clicked on position #%s of Section %s", sectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
private final TextView tvTitle;
HeaderViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
}
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final ImageView imgItem;
private final TextView tvItem;
ItemViewHolder(View view) {
super(view);
rootView = view;
imgItem = (ImageView) view.findViewById(R.id.imgItem);
tvItem = (TextView) view.findViewById(R.id.tvItem);
}
}
}
use structure similar to
public class MultiArray<T> {
List<ItemGroup> lists = new ArrayList<>();
public void addList(String headerText, List<T> list) {
lists.add(new ItemGroup(headerText, list));
}
public int itemCount() {
int count = 0;
for (ItemGroup group : lists) {
count += group.count();
}
return count;
}
public T getItem(int position) {
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.item(position - count);
}
count += group.count();
}
return null;
}
public int getGroupIndex(int position) {
int count = 0;
int groupIndex = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return groupIndex;
}
count += group.count();
groupIndex++;
}
return -1;
}
public String getHeaderText(int position){
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.headerText;
}
count += group.count();
}
return "";
}
class ItemGroup {
public final String headerText;
public final List<T> list;
public ItemGroup(String headerText, List<T> list) {
this.headerText = headerText;
this.list = list;
}
public int count() {
return list.size();
}
public T item(int position) {
return list.get(position);
}
}
}
you can optimize it for faster performance

View Pager inside Recycler view not showing the data in android

I need to make a ecommerce app type screen with multiple viewpager and recycler views.
I implemented it but my 1 out of 2 view pager is visible in recycler view and once I rotate the device, my first view pager also disappear.
My Activity:
public class MainActivity extends AppCompatActivity {
private List<ProductEntity> productEntities = new ArrayList<>();
private RecyclerView productlist;
private HomeAdapter homeAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
productlist = (RecyclerView)findViewById(R.id.mainlist);
//productlist.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
productlist.setLayoutManager(mLayoutManager);
homeAdapter = new HomeAdapter(this,getSupportFragmentManager(),productEntities);
productlist.setAdapter(homeAdapter);
new ParserJsonTask().execute();
}
public String loadJSONFromAsset() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"f_two.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private class ParserJsonTask extends AsyncTask<Void, Integer, List<ProductEntity>> {
#Override
protected List<ProductEntity> doInBackground(Void... params) {
try{
return JsonParser.getInstance().parseJson(loadJSONFromAsset());
}catch(Exception e){
Log.d("Exception", e.toString());
}
return null;
}
#Override
protected void onPostExecute(List<ProductEntity> result) {
Log.e("Length",""+result.size());
if(result != null) {
productEntities = result;
homeAdapter.setProduct(productEntities);
}
}
}
My view pager Fragment:
public class ImageFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_IMAGE_URL = "image_url";
private Context context;
private String image_url;
public ImageFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ImageFragment newInstance(String image) {
ImageFragment fragment = new ImageFragment();
Bundle args = new Bundle();
args.putString(ARG_IMAGE_URL, image);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
image_url = getArguments().getString(ARG_IMAGE_URL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.image);
Log.e("Pager Item Image",""+image_url);
if(!TextUtils.isEmpty(image_url))
Picasso.with(context).load(image_url).into(image);
return rootView;
}
}
My Main adapter for recycler view:
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ProductEntity> productEntities;
private Context context;
private FragmentManager fragmentManager;
private OnItemClickListener mItemClickListener;
private static final int TYPE_FIRST = 0;
private static final int TYPE_SECOND = 1;
private static final int TYPE_THIRD = 2;
private static final String TEMPLATE_FIRST ="product-template-1";
private static final String TEMPLATE_SECOND ="product-template-2";
private static final String TEMPLATE_THIRD ="product-template-3";
public HomeAdapter(Context context , FragmentManager fragmentManager ,List<ProductEntity> productEntities) {
this.productEntities = productEntities;
this.context = context;
this.fragmentManager = fragmentManager;
}
#Override
public int getItemCount() {
Log.e("Item count",""+productEntities.size());
return productEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof ImageViewHolder) {
ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
Log.e("Template Item Image",""+productEntity.getItemEntities().get(0).getImage());
Picasso.with(context).load(productEntity.getItemEntities().get(0).getImage()).into(imageViewHolder.imageView);
} else if(holder instanceof PagerViewHolder) {
PagerViewHolder pagerViewHolder = (PagerViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
pagerViewHolder.viewPager.setAdapter(new PagerAdapter(fragmentManager,productEntity.getItemEntities()));
} else if (holder instanceof HorizontalViewHolder) {
HorizontalViewHolder horizontalViewHolder = (HorizontalViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalViewHolder.recyclerView.setLayoutManager(linearLayoutManager);
horizontalViewHolder.recyclerView.setAdapter(new SliderAdapter(context,productEntity.getItemEntities()));
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if(viewType == TYPE_FIRST) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_image, parent, false);
return new ImageViewHolder (v);
} else if(viewType == TYPE_SECOND) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_horizontal, parent, false);
return new HorizontalViewHolder (v);
} else {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_pager, parent, false);
return new PagerViewHolder(v);
}
}
#Override
public int getItemViewType (int position) {
if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_FIRST)) {
Log.e("Item type",""+TYPE_FIRST);
return TYPE_FIRST;
} else if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_SECOND)) {
Log.e("Item type",""+TYPE_SECOND);
return TYPE_SECOND;
} else {
Log.e("Item type",""+TYPE_THIRD);
return TYPE_THIRD;
}
}
class PagerViewHolder extends RecyclerView.ViewHolder {
protected ViewPager viewPager;
public PagerViewHolder (View itemView) {
super (itemView);
this.viewPager = (ViewPager) itemView.findViewById (R.id.viewpager);
}
}
class ImageViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
public ImageViewHolder (View itemView) {
super (itemView);
this.imageView = (ImageView) itemView.findViewById (R.id.image);
}
}
public class HorizontalViewHolder extends RecyclerView.ViewHolder {
protected RecyclerView recyclerView;
public HorizontalViewHolder(View v) {
super(v);
recyclerView = (RecyclerView)v.findViewById(R.id.horizontallist);
}
}
public void setProduct(List<ProductEntity> data) {
productEntities.clear();
productEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
My view pager adapter:
public class PagerAdapter extends FragmentPagerAdapter {
private List<ItemEntity> itemEntities;
public PagerAdapter(FragmentManager fm, List<ItemEntity> itemEntities) {
super(fm);
this.itemEntities = itemEntities;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return ImageFragment.newInstance(itemEntities.get(position).getImage());
}
#Override
public int getCount() {
// Show 3 total pages.
return itemEntities.size();
}
}
My horizontal recyclerview adapter:
public class SliderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ItemEntity> itemEntities;
private Context context;
private OnItemClickListener mItemClickListener;
public SliderAdapter(Context context , List<ItemEntity> notesEntities) {
this.itemEntities = notesEntities;
this.context = context;
}
#Override
public int getItemCount() {
return itemEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
ItemEntity itemEntity = itemEntities.get(position);
itemViewHolder.productName.setText(itemEntity.getLabel());
Log.e("Item Image",""+itemEntity.getImage());
if(!TextUtils.isEmpty(itemEntity.getImage()))
Picasso.with(context).load(itemEntity.getImage()).into(itemViewHolder.productImage);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.recycler_card_layout, parent, false);
return new ItemViewHolder (v);
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
protected TextView productName;
protected ImageView productImage;
public ItemViewHolder(View v) {
super(v);
productName = (TextView) v.findViewById(R.id.product_name);
productImage = (ImageView) v.findViewById(R.id.product_image);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null)
mItemClickListener.onItemClick(v, getAdapterPosition());
}
});
}
}
public void setItems(List<ItemEntity> data) {
itemEntities.clear();
itemEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
Main activity layout:
<RelativeLayout 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="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Horizontal scrolling layout:
<RelativeLayout 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="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/horizontallist"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
View pager layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200dp">
</android.support.v4.view.ViewPager>
</RelativeLayout>
As per my JSON data, it should have 2 view pager inside recycler view and but it is showing only 1 in portrait mode and once I rotate the device, both are disappear. I thing data is not visible inside recycler view as I can see white space in recycler view while scrolling.
Any help would be appreciated.
Simple change :
extends FragmentPagerAdapter
to
extends FragmentStatePagerAdapter

RecyclerView in RecyclerVIew

I want to create nested RecyclerViews and the problem is that only parent is showing.
Parent Adapter
public class SectionsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
List<Section> mSections;
public SectionsAdapter(Context context, List<Section> sections) {
mContext = context;
mSections = sections;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_section, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) {
Section section = mSections.get(pos);
if (holder instanceof SectionViewHolder) {
SectionViewHolder sectionVH = (SectionViewHolder) holder;
sectionVH.mTitle.setText(section.getTitle());
LinearLayoutManager manager = new LinearLayoutManager(mContext);
sectionVH.mPreferences.setLayoutManager(manager);
PreferencesAdapter preferencesAdapter = new PreferencesAdapter(mContext, section.getPreferences());
sectionVH.mPreferences.setAdapter(preferencesAdapter);
sectionVH.mPreferences.getAdapter().notifyDataSetChanged();
}
}
#Override
public int getItemViewType(int pos) {
return 0;
}
#Override
public int getItemCount() {
return mSections.size();
}
}
Child Adapter
public class PreferencesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int VIEW_BOOLEAN = 0;
public static final int VIEW_INT = 1;
Context mContext;
List<Preference> mPreferences;
public PreferencesAdapter(Context context, List<Preference> preferences) {
mContext = context;
mPreferences = preferences;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_preference_boolean, parent, false);
return new BooleanPreferenceViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) {
Preference preference = mPreferences.get(pos);
if (holder instanceof BooleanPreferenceViewHolder) {
BooleanPreferenceViewHolder booleanPreferenceVH = (BooleanPreferenceViewHolder) holder;
booleanPreferenceVH.mPreferenceTitle.setText(preference.getTitle());
booleanPreferenceVH.mPreferenceExplanation.setText(preference.getExplanation());
booleanPreferenceVH.mBooleanSwitch.setChecked((Boolean) preference.getValue());
}
}
#Override
public int getItemViewType(int pos) {
return VIEW_BOOLEAN;
}
#Override
public int getItemCount() {
return mPreferences.size();
}
}
Parent View Holder
public class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public RecyclerView mPreferences;
public SectionViewHolder(View v) {
super(v);
mTitle = (TextView) v.findViewById(R.id.sectionTitle);
mPreferences = (RecyclerView) v.findViewById(R.id.preferences);
}
}
Child View Holder
public class BooleanPreferenceViewHolder extends RecyclerView.ViewHolder {
public TextView mPreferenceTitle;
public TextView mPreferenceExplanation;
public Switch mBooleanSwitch;
public BooleanPreferenceViewHolder(View v) {
super(v);
mPreferenceTitle = (TextView) v.findViewById(R.id.preferenceTitle);
mBooleanSwitch = (Switch) v.findViewById(R.id.booleanSwitch);
mPreferenceExplanation = (TextView) v.findViewById(R.id.preferenceExplanation);
}
}
So I noticed that is showing only parent title and its recyclerview is empty. Also child onBindViewHolder method is not calling.
You can achieve what you want with only one RecyclerView, overriding the getItemViewType method properly. You can see an example here.
Below is an example using your Section, Preference and BooleanPreferenceViewHolder classes with the library SectionedRecyclerViewAdapter.
First create a section class:
class MySection extends StatelessSection {
String title;
List<Preference> mPreferences;
public MySection(String title, List<Preference> preferences) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_footer, R.layout.section_item);
this.title = title;
this.mPreferences = preferences;
}
#Override
public int getContentItemsTotal() {
return mPreferences.size(); // number of items of this section
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new BooleanPreferenceViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
BooleanPreferenceViewHolder itemHolder = (BooleanPreferenceViewHolder) holder;
// bind your view here
itemHolder.mPreferenceExplanation.setText(mPreference.get(position).getExplanation());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
MySection section1 = new MySection(mSections.get(0).getTitle(), mSections.get(0).getPreferences());
MySection section2 = new MySection(mSections.get(1).getTitle(), mSections.get(1).getPreferences());
// Add your Sections
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Categories

Resources