See sanpshot here
jObject = new JSONObject(result);
JSONObject resultObj = jObject.getJSONObject("result");
for(int i = 0; i < firstproducts.size(); i++) {
try {
title = firstproducts.get(i).getString("category");
categoryIcon = firstproducts.get(i).getString("icon_img");
Log.e("For I","Value : "+title);
for(int j = 0; j < secondproducts.size(); j++) {
if(title.equalsIgnoreCase(secondproducts.get(j).getString("category"))){
categoryIcon = secondproducts.get(j).getJSONObject("info").getString("img");
JSONArray products=null;
products = firstproducts.get(j).gptJSONArray("Products"); if(products!=null) {
for (int k = 0; k < products.length(); k++) {
JSONObject jsonObj = products.getJSONObject(k);
content = jsonObj.getString("description");
points = jsonObj.getString("points");
imageUrl = jsonObj.getString("image");
secondarraylist.add(new ChildModel(content,points,rating,imageUrl));
}
}
mainarraylist.add(new MainModel(title,categoryIcon,secondarraylist));
finally i set this above main arraylist to recyclerview adapter
------------------------------- ---------
Mian Model class as below -child model inside 3 string values will be there.
public class MainModel {
String title;
String categoryIcon;
private List<ChildModel> ChildItems;
public MainModel() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategoryIcon() {
return categoryIcon;
}
public void setCategoryIcon(String categoryIcon) {
this.categoryIcon = categoryIcon;
}
public List<ChildModel> getChildItems() {
return ChildItems;
}
public void setItems(List<ChildModel> ChildItems) {
this.ChildItems = ChildItems;
}
}
---------------------------------------
Main adapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ProductViewHolder> {
private final Context mContext;
List<MainModel> maindata;
public MainAdapter(Context mContext, List<MainModel> ProductList) {
this.mContext = mContext;
this.maindata=ProductList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.product_list_store, parent, false);
return new ProductViewHolder(view);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public final ImageView categoryIcon;
public final ImageView leftArrow;
public final ImageView rightArrow;
public final View categoryDiver;
private ChildAdapter horizontalAdapter;
private RecyclerView horizontalList;
private LinearLayoutManager llm;
public ProductViewHolder(View view) {
super(view);
Context context = itemView.getContext();
title = (TextView) view.findViewById(R.id.product_textForHeader);
categoryIcon = (ImageView) view.findViewById(R.id.product_Iconimageview);
leftArrow = (ImageView)view.findViewById(R.id.product_leftside_arrow);
rightArrow = (ImageView)view.findViewById(R.id.product_rightside_arrow);
categoryDiver = view.findViewById(R.id.product_Divider_view);
horizontalList = (RecyclerView) itemView.findViewById(R.id.horizontal_layout);
llm = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
horizontalList.setLayoutManager(llm);
horizontalAdapter = new ChildAdapter(context);
horizontalList.setAdapter(horizontalAdapter);
}
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, int position) {
holder.title.setText(maindata.get(position).getTitle());
holder.horizontalAdapter.setData(maindata.get(position).getStoreItems()); // List of Strings
holder.horizontalAdapter.setRowIndex(position);
holder.leftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("left");
if (holder.llm.findFirstCompletelyVisibleItemPosition() > 0){
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() - 1);
}
}
});
holder.rightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("right");
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() + 1);
}
});
if(position == maindata.size()-1)
holder.categoryDiver.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
//return 0;
return maindata.size();
}
}
-------------------------------------------
ChildAdapter
public class ChildAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private List<ChildModel> childdata;
private ImageLoader imageLoader;
private int mRowIndex = -1;
public ChildAdapter(Context context) {
this.context = context;
}
public void setData(List<ChildModel> data) {
if (childdata != data) {
childdata = data;
notifyDataSetChanged();
}
}
publindex;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
public final TextView content;
public final TextView rating;
public final TextView points;
public final NetworkImageView img_item;
public final ImageView img_rating;
public ItemViewHolder(View view) {
super(view);
content = (TextView) view.findViewById(R.id.category_item_title);
rating = (TextView) view.findViewById(R.id.text_rating);
points = (TextView) view.findViewById(R.id.category_points);
img_item = (NetworkImageView) view.findViewById(R.id.category_item_imageView);
img_rating= (ImageView) view.findViewById(R.id.img_rating);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View itemView = LayoutInflater.from(context).inflate(R.layout.store_category_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(itemView);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewholder, int position) {
ItemViewHolder holder=(ItemViewHolder)viewholder;
holder.content.setText(childdata.get(position).getContent());
holder.points.setText(childdata.get(position).getPoints());
holder.rating.setText(childdata.get(position).getRating());
holder.itemView.setTag(position);
}
#Override
public int getItemCount() {
return childdata.size();
}
}
I am doing a project with horizontal and vertical recyclerview same like a play store. I have done all the designs like 2 adapters and 2 model class.
The problem is I parsed json and set all the data to 2 array list so all the data come to horizontal adapters. how to set horizontal values from arraylist according to below heading thats dynamic.
This is my API: bikes, cars, trucks; I need to set this data vertical recyclerview heading and inside products array that is horizontal recyclerview:
I can tell you the approach-->Get all child json in the main array-->then in each of these json object get the products jsonobject and set them accordingly
Related
Hi I wanna set my recycleview clickable . for example when click on recycleview's each view toast its parameters (like its name) . please don't rank negative I'm a newbie.
this is my mainclass to show recycleview
public class HomeFragment2 extends Fragment {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
View view ;
int RecyclerViewItemPosition ;
ArrayList<String> ImageTitleNameArrayListForClick;
String ID = "id";
String SECTION = "section";
String TIME = "time";
String NAME = "name";
Button button;
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public static HomeFragment2 newInstance() {
return new HomeFragment2();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home2, container, false);
GetDataAdapter1 = new ArrayList<>();
recyclerView =v.findViewById(R.id.recyclerView1);
progressBar =v.findViewById(R.id.progressBar1);
button =v.findViewById(R.id.button);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
return v;
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(URLS.recycle_fetch,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(ID));
GetDataAdapter2.setName(json.getString(SECTION));
GetDataAdapter2.setSubject(json.getString(TIME));
GetDataAdapter2.setPhone_number(json.getString(NAME));
// Adding image title name in array to display on RecyclerView click event.
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getActivity());
recyclerView.setAdapter(recyclerViewadapter);
}
}
and my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
cardView = (CardView) view.findViewById(R.id.mainCard);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
holder.Id.setText(getDataAdapter1.getName());
holder.Section.setText(String.valueOf(getDataAdapter1.getId()));
holder.Time.setText(getDataAdapter1.getPhone_number());
holder.Name.setText(getDataAdapter1.getSubject());
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView Id;
public TextView Section;
public TextView Time;
public TextView Name;
public ViewHolder(View itemView) {
super(itemView);
Id =itemView.findViewById(R.id.textView2);
Section =itemView.findViewById(R.id.textView4);
Time =itemView.findViewById(R.id.textView6);
Name =itemView.findViewById(R.id.textView8);
}
}
}
any body can help me? i wanna get cardview's parameters when click each of them .
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
//////////////////////////////////here you define your layout you wanna be clicked/////////////////////////
cardView = (CardView) view.findViewById(R.id.mainCard);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
holder.Id.setText(getDataAdapter1.getName());
holder.Section.setText(String.valueOf(getDataAdapter1.getId()));
holder.Time.setText(getDataAdapter1.getPhone_number());
holder.Name.setText(getDataAdapter1.getSubject());
///////////////////////////////// and here you add your on click listener////////////////////////////////
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView Id;
public TextView Section;
public TextView Time;
public TextView Name;
public ViewHolder(View itemView) {
super(itemView);
Id =itemView.findViewById(R.id.textView2);
Section =itemView.findViewById(R.id.textView4);
Time =itemView.findViewById(R.id.textView6);
Name =itemView.findViewById(R.id.textView8);
}
}
}
I am new here, I have an activity that contains ViewPager with two Fragments. Each Fragment has a RecyclerView. on selecting a tab through OnTabSelection items in the RecyclerView gets repeated. I can't understand what is causing this problem.
I am using DataHandler to save the data because I have to use this data in other activities as well.
class DataHandler {
private ArrayList<MenuHolder> listOfItemsFromJson;
private static DataHandler mInstance = null;
static public DataHandler getInstance() {
if (null == mInstance) {
mInstance = new DataHandler();
}
return mInstance;
}
public DataHandler() {
listOfItemsFromJson = new ArrayList<>();
}
public ArrayList<MenuHolder> getListOfItemsFromJson() {
return listOfItemsFromJson;
}
public void clearList() {
listOfItemsFromJson.clear();
}
public void addData(MenuHolder holder) {
listOfItemsFromJson.add(holder);
}
public MenuHolder getData(int position) {
return listOfItemsFromJson.get(position);
}
public void removeData(int position) {
listOfItemsFromJson.remove(getData(position));
}
public int size() {
return listOfItemsFromJson.size();
}
}
Here is my Fragment
class ComboRecycler extends Fragment {
private ArrayList<Integer> index = new ArrayList<>();
private LinearLayout mViewCartLayout;
private RelativeLayout relativeLayout;
private RecyclerView recyclerView;
RecyclerView.Adapter recyclerAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_combo, container, false);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout1);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recylerViewLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recylerViewLayoutManager);
new FetchTask().execute();
return view;
}
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
#Override
protected JSONArray doInBackground(Void... params) {
JSONArray jsonArray;
........
}
#Override
protected void onPostExecute(JSONArray result) {
if (result != null) {
try {
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getData(i).isCombo()) {
DataHandler.getInstance().removeData(i);
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject mJsonObject = result
.getJSONObject(i);
MenuHolder mDataHolder = new MenuHolder();
......
mDataHolder.setCombo(true);
mDataHolder.setItemCount("0");
DataHandler.getInstance().addData(mDataHolder);
}
setAdapter();
} catch (Exception e) {
}
}
}
}
private void setAdapter() {
index.clear();
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getListOfItemsFromJson().get(i).isCombo()) {
index.add(i);
}
}
recyclerComboAdapter = new RecyclerComboAdapter(getActivity(), index);
recyclerView.setAdapter(recyclerComboAdapter);
}
}
Here is my RecyclerAdapter
class RecyclerComboAdapter extends RecyclerView.Adapter<RecyclerComboAdapter.ViewHolder> {
Context context;
View view1;
ViewHolder viewHolder1;
ArrayList<Integer> index;
LinearLayout mViewCart;
Recycler recycler;
private AQuery mQuery;
public RecyclerComboAdapter(Context context1, ArrayList<Integer> index) {
this.index = index;
context = context1;
mQuery = new AQuery(context1);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view1 = LayoutInflater.from(context).inflate(R.layout.combo_meals_adapter, parent, false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final int pos = position;
MenuHolder menuHolder =DataHandler.getInstance().getData(index.get(position));
holder.itemName.setText(menuHolder.getItemname());
holder.itemPrice.setText(menuHolder.getItemprice());
mQuery.id(holder.imageView).image(menuHolder.getItemPicture());
holder.counter.setText(menuHolder.getItemCount());
}
#Override
public int getItemCount() {
return index.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView add, minus, plus, counter, itemName, itemPrice;
ViewHolder(View v) {
super(v);
itemName = (TextView) v.findViewById(R.id.itemnametxt);
imageView = (ImageView) v.findViewById(R.id.image);
itemPrice = (TextView) v.findViewById(R.id.price);
minus = (TextView) v.findViewById(R.id.minus);
plus = (TextView) v.findViewById(R.id.plus);
counter = (TextView) v.findViewById(R.id.count);
add = (TextView) v.findViewById(R.id.addtxt);
}
}
}
After swiping the list multiple times I am seeing repeated list items. Please help me with this problem. Thanks in advance.
Unable to add second child in Recyclerview I am passing two different arrays to RecyclerAdapter to display two child layout with different data and views.Is there any solution to add different child layout using same header layout.I added horizontal Recyclerview in vertical Recyclerview and I want to display details like I attached the image
private void setupRecyclerView(RecyclerView recyclerView) {
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter();
int[] images = new int[]{
R.drawable.finance,
R.drawable.business,
R.drawable.financejob,
R.drawable.ecomchallenges
};
ArrayList<ChildView> childViews = new ArrayList<>();
childViews.add(new ChildView(images[0], "The \"Best\" Startup Pitch Deck - How To Raise Venture Capital", "$100"));
childViews.add(new ChildView(images[1], "An Entire MBA in 1 Course:Award Winning Business School Prof", "$100"));
childViews.add(new ChildView(images[2], "What Finance Job is for You? Explanation of 14 Finance Roles", "$100"));
childViews.add(new ChildView(images[3], "Learn To Build Beautiful HTML5 And CSS3 Websites In 1 Month", "$100"));
int[] courseImage = new int[] {
R.drawable.php,
R.drawable.development,
R.drawable.web,
R.drawable.java
};
ArrayList<CourseByType> courseByTypes = new ArrayList<>();
courseByTypes.add(new CourseByType("Technology", courseImage[0]));
courseByTypes.add(new CourseByType("Business", courseImage[1]));
courseByTypes.add(new CourseByType("Photography", courseImage[2]));
courseByTypes.add(new CourseByType("Development", courseImage[3]));
Log.d("","Above adapter");
recyclerAdapter.addItem(new GroupView("Business", childViews));
Log.d("","Below Child");
recyclerAdapter.addCourseByType(new CourseByHeader("Technology", courseByTypes));
Log.d("","Below Course");
recyclerView.setAdapter(recyclerAdapter);
}
This is the main fragment where I set the values to two different
arraylist ArrayList<ChildView> childViews = new ArrayList<>()
and
ArrayList<CourseByType> courseByTypes = new ArrayList<>()
Values of child views are passing properly but CourseByType values are not passing.This is the adapter class for this fragment class.
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<PassValues> containerArrayList;
ArrayList<GroupView> groupViews;
ArrayList<CourseByHeader>courseByHeaders;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.group_title, parent, false);
return new ViewHolder(view);
}
public RecyclerAdapter(){
containerArrayList = new ArrayList<>();
groupViews = new ArrayList<>();
courseByHeaders = new ArrayList<>();
}
public void addContainer(PassValues container){
containerArrayList.add(container);
}
public void addItem(GroupView groupView){
Log.d("","Inside Group method");
groupViews.add(groupView);
}
public void addCourseByType(CourseByHeader courseByHeader){
Log.d("","Inside Course method");
courseByHeaders.add(courseByHeader);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("", "Pass Values out of IF" + position);
ChildViewAdapter childViewAdapter = new ChildViewAdapter();
if(position == 0){
GroupView groupView = groupViews.get(position);
holder.title.setText(groupView.getTitle());
Log.d("", "Passing Values" + groupView.getTitle());
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
childViewAdapter.addChild(groupView.getChildViewList());
holder.recyclerView.setAdapter(childViewAdapter);
}
if (position == 1) {
CourseByHeader courseByHeader = courseByHeaders.get(position);
holder.title.setText(courseByHeader.getTitle());
Log.d("", "Passing Values" + courseByHeader.getTitle());
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
childViewAdapter.addCourse(courseByHeader.getCourseByTypes());
holder.recyclerView.setAdapter(childViewAdapter);
}
}
#Override
public int getItemCount() {
if(getItemViewType(0) == TYPE_HEADER)
return groupViews.size() ;
if (getItemViewType(1) == TYPE_ITEM)
return courseByHeaders.size();
else return -1;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
RecyclerView recyclerView;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.course_title);
recyclerView = (RecyclerView)itemView.findViewById(R.id.group_recycler);
}
}
}
This RecyclerAdapter contains one RecyclerView in that first row has one image and 3 textviews and 2nd row has 1 ImageView and 1 TextView. At position first,one image and 3 textviews are shown but it's not going on 2nd view
This is the view I getting after run on emulator.
This are two child for RecyclerViews
ChildView.java
public class ChildView {
int image;
String course, price;
public ChildView(int image, String course, String price) {
this.image = image;
this.course = course;
this.price = price;
}
public int getImage() {
return image;
}
public String getCourse() {
return course;
}
public String getPrice() {
return price;
}
}
CourseByType.java
public class CourseByType {
String courseName;
int courseImage;
public CourseByType(String courseName, int courseImage) {
this.courseName = courseName;
this.courseImage = courseImage;
}
public String getCourseName() {
return courseName;
}
public int getCourseImage() {
return courseImage;
}
}
CourseByHeader.java
public class CourseByHeader {
String title;
ArrayList<CourseByType> courseByTypes;
public CourseByHeader(String title, ArrayList<CourseByType> courseByTypes) {
this.title = title;
this.courseByTypes = courseByTypes;
}
public String getTitle() {
return title;
}
public ArrayList<CourseByType> getCourseByTypes() {
return courseByTypes;
}
}
GroupView.java
public class GroupView {
String title;
ArrayList<ChildView> childViewList;
String courseBy;
ArrayList<CourseByType> courseByTypes;
public GroupView(String title, ArrayList<ChildView> childViewList) {
this.title = title;
this.childViewList = childViewList;
}
public String getTitle() {
return title;
}
public ArrayList<ChildView> getChildViewList() {
return childViewList;
}
}
Groupview and CouseByType class have title and child list for recycleradapter
ChildViewAdapter.java
public class ChildViewAdapter extends RecyclerView.Adapter {
ArrayList<ChildView> childViewList;
ArrayList<CourseByType> courseByTypes;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public class ViewHolder extends RecyclerView.ViewHolder{
public ViewHolder(View itemView) {
super(itemView);
}
}
public class GroupHolder extends ViewHolder {
public ImageView iamView;
public TextView course, price;
public GroupHolder(View itemView) {
super(itemView);
iamView = (ImageView) itemView.findViewById(R.id.course_image);
course = (TextView) itemView.findViewById(R.id.course_by);
price = (TextView) itemView.findViewById(R.id.price);
}
}
public void addCourse(ArrayList<CourseByType> courseByType){
courseByTypes = courseByType;
}
public void addChild(ArrayList<ChildView> childView){
childViewList = childView;
}
public class Course extends ViewHolder {
public ImageView courseTypeImage;
public TextView courseType;
public Course(View itemView) {
super(itemView);
courseTypeImage = (ImageView)itemView.findViewById(R.id.course_image);
courseType = (TextView)itemView.findViewById(R.id.course_name_course);
}
}
public ChildViewAdapter() {
childViewList = new ArrayList<>();
courseByTypes = new ArrayList<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
RecyclerView.ViewHolder vh = null;
View v;
if(viewType == TYPE_HEADER){
v = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return new GroupHolder(v);
}if(viewType == TYPE_ITEM){
v = LayoutInflater.from(context).inflate(R.layout.type_of_courses, parent, false);
return new Course(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof GroupHolder){
Log.d("","instance of Group Holder");
ChildView childView = childViewList.get(position);
((GroupHolder)holder).iamView.setImageResource(childView.getImage());
((GroupHolder)holder).course.setText(childView.getCourse());
((GroupHolder)holder).price.setText(childView.getPrice());
return;
}
if(holder instanceof Course){
Log.d("","instance of Course ");
CourseByType courseByType = courseByTypes.get(position);
((Course)holder).courseTypeImage.setImageResource(courseByType.getCourseImage());
((Course)holder).courseType.setText(courseByType.getCourseName());
return;
}
}
#Override
public int getItemCount() {
int size;
if(childViewList.size()>0){
return size = childViewList.size();
}else return size = courseByTypes.size();
}
#Override
public int getItemViewType(int position) {
if(childViewList.size() != 0 && childViewList.size()>0){
return TYPE_HEADER;
}else return TYPE_ITEM;
}
}
This childview adapter has two view types first is one image and 3 text and second view type contain one image and one text.When I pass values from fragment only first view type get displayed and second view type not gets value from fragment.
To show multiple different views in a recyclerview, you have to override getItemViewType() in the recyclerview adapter.
//getItemViewType enables dynamic viewholder creation
#Override
public int getItemViewType(int position) {
//you will need to add a integer with variable name viewTypeCode
//for view1 set viewTypeCode = 100 and for view2 set viewTypeCode = 200
viewTypeCode = itemList.get(position).getViewTypeCode();
return viewTypeCode;
}
This is how the onCreateViewHolder will be different for multiple viewtypes. You will have to modify yours like this
#Override
public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 100: return new FeedViewHolder(layoutInflater.inflate(R.layout.v1, parent, false),100);
case 200: return new FeedViewHolder(layoutInflater.inflate(R.layout.v2, parent, false),200);
}
return null;
}
OnBindViewHolder will be similarly modified
#Override
public void onBindViewHolder(final FeedViewHolder holder, int position) {
viewTypeCode = itemList.get(position).getViewTypeCode();
switch ( viewTypeCode) {
case 100:
//your code for v1
case 200:
//your code for v2
}
}
Similarly the ViewHolder class is modified
class FeedViewHolder extends RecyclerView.ViewHolder{
//declare variables here
public FeedViewHolder(View v, int viewType) {
super(v);
switch (viewType) {
//instead of itemView.findViewById you will have to use v.findViewById
case 100:
//your code for v1
case 200:
//your code for v2
}
}
For further reference refer to this SO answer
Don't pass two separate list.Make a custom class like this-
class MyClass {
int viewTypeCode;
CustomClass1 c1;
CustomClass2 c2;
//add the setter getter
}
In your activity while preparing the data.
List<MyClass> itemList = new ArrayList<>();
//put whatever logic you need to make the order of the list
//if CustomClass1 object is put then setViewTypeCode(100), setCustomClass2 = null
//if CustomClass2 object is put then setViewTypeCode(200), setCustomClass1 = null
After data is built, then send this to the adapter.
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
I have some items in my adapter but nothing is shown in the RecyclerView.
Adapter
public class WorkOrderAdapter extends RecyclerView.Adapter<WorkOrderViewHolder> {
private List<WorkOrder> orders = new LinkedList<>();
public void setData(List<WorkOrder> orders) {
this.orders = orders;
}
#Override
public WorkOrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_workorder, parent, false);
return new WorkOrderViewHolder(view);
}
#Override
public void onBindViewHolder(WorkOrderViewHolder holder, int position) {
WorkOrder order = orders.get(position);
holder.bind(order);
}
#Override
public int getItemCount() {
return orders.size();
}
}
ViewHolder
public class WorkOrderViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
private TextView date;
public WorkOrderViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title_textview);
description = (TextView) view.findViewById(R.id.description_textview);
date = (TextView) view.findViewById(R.id.date_textview);
}
public void bind(WorkOrder order) {
title.setText("Test");
description.setText("Test");
date.setText("Test");
}
}
Activity (Using AndroidAnnotations)
#EActivity(R.layout.activity_workorders)
#OptionsMenu(R.menu.activity_workorders)
public class WorkOrdersActivity extends ToolbarActivity {
#ViewById(R.id.orders_recyclerview)
RecyclerView ordersList;
List<WorkOrder> orders = new LinkedList<>();
private WorkOrderAdapter adapter;
{
adapter = new WorkOrderAdapter();
orders.add(new WorkOrder());
orders.add(new WorkOrder());
orders.add(new WorkOrder());
adapter.setData(orders);
}
#AfterViews
public void initViews() {
ordersList.setAdapter(adapter);
}
}
Please add the LayoutManager to the RecyclerView and try again
ordersList.setLayoutManager(new LinearLayoutManager(this));
ordersList.setAdapter(adapter);