Why my page is lagging while click on "Daily Meal" - java

I am working on food delivery application. I have four tab in menu bar Home, Daily Meal, Favourite and My Cart. My all tab is work well but when I click on Daily Meal my page is rendering. What can I try next?
Here is my code:
daily_meal_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
tools:context=".ui.DailyMeal.DailyMealFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/daily_meal_rec"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
daily_meal_ver.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<ImageView
android:id="#+id/imgview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="#drawable/breakfast"
android:foreground="#drawable/blur"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/amita_bold"
android:text="Dinner"
android:textColor="#color/white"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/imgview"
app:layout_constraintEnd_toEndOf="#+id/imgview"
app:layout_constraintStart_toStartOf="#+id/imgview"
app:layout_constraintTop_toTopOf="#+id/imgview"
app:layout_constraintVertical_bias="0.3" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/amita"
android:text="Choose your best dinner"
android:textColor="#color/white"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/names" />
<TextView
android:id="#+id/discounts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/off_back"
android:padding="2sp"
android:text=" 20% OFF "
android:textColor="#FFFFFF"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/imgview"
app:layout_constraintStart_toStartOf="#+id/imgview"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.821" />
</androidx.constraintlayout.widget.ConstraintLayout>
DailyMealModel.java
public class DailyMealModel {
int image;
String name;
String discount;
String description;
// getter setter and constructor
}
DailyMealFragment.java
public class DailyMealFragment extends Fragment {
RecyclerView recyclerView;
List<DailyMealModel> dailyMealModels;
DailyMealAdapter dailyMealAdapter;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.daily_meal_fragment,container,false);
recyclerView = root.findViewById(R.id.daily_meal_rec);
dailyMealModels = new ArrayList<>();
dailyMealModels.add(new DailyMealModel(R.drawable.breakfast,"Breakfast","30% OFF","Description Description"));
dailyMealModels.add(new DailyMealModel(R.drawable.lunch,"Lunch","15% OFF","Description Description"));
dailyMealAdapter = new DailyMealAdapter(getContext(),dailyMealModels);
recyclerView.setAdapter(dailyMealAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
}
DailyMealAdapter.java
public class DailyMealAdapter extends RecyclerView.Adapter<DailyMealAdapter.viewholder> {
Context context;
List<DailyMealModel> list;
public DailyMealAdapter(Context context, List<DailyMealModel> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new viewholder(LayoutInflater.from(parent.getContext()).inflate(R.layout.daily_meal_ver,parent,false));
}
#Override
public void onBindViewHolder(#NonNull viewholder holder, int position) {
holder.img.setImageResource(list.get(position).getImage());
holder.name.setText(list.get(position).getName());
holder.discount.setText(list.get(position).getDiscount());
holder.description.setText(list.get(position).getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public class viewholder extends RecyclerView.ViewHolder {
ImageView img;
TextView name,discount,description;
public viewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imgview);
name = itemView.findViewById(R.id.names);
description = itemView.findViewById(R.id.desc);
discount = itemView.findViewById(R.id.discounts);
}
}
}
Snapshot

As your attached screenshot,
please make sure all images and icons used in the app are lower sizes even loading dynamic images for that you can use tinypng.com or tinyjpg.com
also, using pagination in RecyclerView will improve your app performance.
and make sure JSON/XML list response is minimal.

Related

RecyclerView Items are not showing

FolderListAdapter Code
public class FolderListAdapter extends RecyclerView.Adapter<FolderListAdapter.myViewHolder> {
private final Context context;
private final ArrayList<Folder> folderList;
public FolderListAdapter(Context context, ArrayList<Folder> folderList) {
this.context = context;
this.folderList = folderList;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.folder_view, parent, false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
Folder folder = folderList.get(position);
Glide.with(context).load(folder.getFolder()).into(holder.imageView);
holder.folder_name.setText(folder.getFolder().getName());
holder.folder_item_count.setText(folder.getFilesList().size() + " Items");
}
#Override
public int getItemCount() {
return folderList.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
private final ShapeableImageView imageView;
private final TextView folder_name;
private final TextView folder_item_count;
public myViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.folder_image_view);
folder_name = itemView.findViewById(R.id.folder_name_text_view);
folder_item_count = itemView.findViewById(R.id.folder_items_count_text_view);
}
}
}
MainActivity Code for RecyclerView
FolderListAdapter adapter = new FolderListAdapter(this, folderList);
RecyclerView recyclerView = binding.folderRecyclerView;
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
XML CODE OF recycler view
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/folder_recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/folder_view" />
folder_view.xml code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/folder_image_view"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="?android:attr/selectableItemBackground"
app:shapeAppearanceOverlay="#style/ShapeAppearanceOverlay.App.CornerSize50Percent"
tools:srcCompat="#tools:sample/backgrounds/scenic" />
<TextView
android:id="#+id/folder_name_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="Camera"
android:textColor="#android:color/primary_text_light"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="#+id/folder_image_view"
app:layout_constraintStart_toStartOf="#+id/folder_image_view"
app:layout_constraintTop_toBottomOf="#+id/folder_image_view" />
<TextView
android:id="#+id/folder_items_count_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="600 Items"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="#+id/folder_name_text_view"
app:layout_constraintTop_toBottomOf="#+id/folder_name_text_view" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_folder.xml layout file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
tools:context=".ui.addFiles.FoldersActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/folder_recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
OUTPUT
The size of folderList is 2
I also check the size of adapter. It is also 2
I also tried by making a new Adapter but it also does not work.
I don't know where I am making mistake and why it is now showing nothing in activity.
Change 1 :
In the xml set attribute android:layout_width="0dp" to android:layout_width="match_parent" and android:layout_height="0dp" to android:layout_height="match_parent"
Change 2 :
In your MainActivity code set LayoutManager to the RecyclerView before setting up adapter. so the code goes this way :
//Defining RecyclerView and setting LayoutManager
RecyclerView recyclerView = binding.folderRecyclerView;
FolderListAdapter adapter = new FolderListAdapter(this, folderList);
//Setting up Adapter
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setAdapter(adapter);

Android Java Set up recyclerview items that are right aligned

I am developing an android chat app and I would like the messages of the user you are chatting with to be aligned to the right and their messages to be aligned to the left. This is the condition that allows you to distinguish who the message belongs to, I can only write it on the bindview holder:
if(model.getUidSender().equals(fAuth.getCurrentUser().getUid()))
But how do I align the item to the right or left?
I have also thought about inflating two different layouts but I should go and operate in the CreateViewHolder in which I would not have the model.getUidSender value. How can I solve this problem?
This is my complete code:
#Override
protected void onStart() {
super.onStart();
CollectionReference collectRefMessage = FirebaseFirestore.getInstance().collection("roomChat")
.document("rooms")
.collection(chatId).document("message")
.collection("messages");
FirestoreRecyclerOptions<getMessage> options
= new FirestoreRecyclerOptions.Builder<getMessage>()
.setQuery(collectRefMessage.limit(1000).orderBy("date", Query.Direction.ASCENDING), getMessage.class)
.build();
FirestoreRecyclerAdapter<getMessage, getASetMsg> firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<getMessage, getASetMsg>(options) {
#Override
protected void onBindViewHolder(#NonNull #NotNull getASetMsg holder, int position, #NonNull #NotNull getMessage model) {
holder.txtMsgText.setText(model.getText());
holder.dateATime.setText(model.getDate());
// uidCh = model.getUidSender();
//if(model.getUidSender().equals(fAuth.getCurrentUser().getUid()))
}
#NonNull
#NotNull
#Override
public getASetMsg onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_chat,parent,false);
getASetMsg viewHolder = new getASetMsg(view);
return viewHolder;
}
};
rView.setAdapter(firestoreRecyclerAdapter);
firestoreRecyclerAdapter.startListening();
}
public static class getASetMsg extends RecyclerView.ViewHolder {
TextView txtMsgText, dateATime;
public getASetMsg(#NonNull View itemView) {
super(itemView);
txtMsgText = itemView.findViewById(R.id.txtMsgText);
dateATime = itemView.findViewById(R.id.dateATime);
}
}
I managed to solve it like this:
if(model.getUidSender().equals(fAuth.getCurrentUser().getUid())) {
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.messageCard.getLayoutParams();
params.gravity = GravityCompat.END; // or GravityCompat.END
holder.messageCard.setLayoutParams(params);
}
So, this is the chat card layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_alignParentEnd="true"
app:cardBackgroundColor="#color/textC"
android:layout_marginTop="10dp"
>
<com.google.android.material.card.MaterialCardView
android:id="#+id/messageCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="#color/textC"
app:cardCornerRadius="20dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtMsgText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi, this is a message"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:textColor="#FFFFFF"
android:layout_marginTop="25dp"
android:layout_marginBottom="20dp"
android:textSize="22dp"/>
<TextView
android:id="#+id/dateATime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:text="32/07/2021 00:00"
android:layout_marginTop="5dp"
android:textColor="#color/white"
android:layout_marginLeft="30dp"
/>
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
</FrameLayout>

Fragment viewpager No adapter attached; skipping layout

I tried a lot of solutions but no solution has worked for me.
I am getting data from the server and showing it inside a recycleview. The data shows fine but shows this error in the logcat
Access denied finding property "persist.vendor.log.tel_dbg"
E/RecyclerView: No adapter attached; skipping layout
E/RecyclerView: No adapter attached; skipping layout
sometimes when I refresh again and again the recyclerview becomes empty.
I am using viewpager consisting of 2 fragments inside a parent fragment.
this recycleview is using in a nested scrollview
some time data not showing
Code snippet:
homebuyer_adapter_recycler=new homebuyer_adapter_recycle(getActivity(), items);
LinearLayoutManager home = new LinearLayoutManager(getActivity());
home.setOrientation(LinearLayoutManager.VERTICAL);
allitemsgrid.setLayoutManager(home);
allitemsgrid.setAdapter(r);
Here is more about
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent,
final int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.items_view,parent,
false);
RecyclerView.LayoutParams lp = new
RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);
ViewHolder viewHolder = new ViewHolder(v);
HERE IS MY item view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
app:cardCornerRadius="6dp"
android:layout_marginBottom="3dp"
app:cardBackgroundColor="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:id="#+id/image_items"
android:scaleType="fitXY"
/>
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:background="#drawable/blackshade"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/items_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:fontFamily="sans-serif-smallcaps"
android:paddingLeft="20dp"
android:text="Message" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="Timing"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:layout_alignParentBottom="true"
android:fontFamily="#font/mylight"
android:layout_alignParentRight="true"
android:textSize="10dp"
android:id="#+id/shoptimming"/>
</RelativeLayout>
<TextView
android:id="#+id/name_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:alpha="0.6"
android:fontFamily="#font/arimo_bold"
android:paddingLeft="20dp"
android:text="Name"
android:textColor="#color/black"
android:textSize="17dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="horizontal">
<TextView
android:id="#+id/minumum_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:drawablePadding="10dp"
android:fontFamily="sans-serif"
android:paddingLeft="20dp"
android:text="Minimum " />
<TextView
android:id="#+id/price_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fontFamily="sans-serif"
android:gravity="left"
android:paddingLeft="20dp"
android:text="charges"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Here is my adapter class
public class homebuyer_adapter_recycle extends RecyclerView.Adapter<homebuyer_adapter_recycle.ViewHolder> {
private ArrayList<seller_information> listData;
private LayoutInflater layoutInflater;
int lastpostition=-1;
Context context;
public homebuyer_adapter_recycle(Context aContext, ArrayList<seller_information> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
context=aContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder
(#NonNull ViewGroup parent, final
int viewType) {
View v = LayoutInflater.from(parent.getContext()).
inflate(R.layout.items_view,parent, false);
ViewHolder viewHolder = new ViewHolder(v);
Log.i("inadapter","calling time");
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
phone_number_shop = listData.get(viewType).getPhonenumber();
homebuyer.Delivery_charges_shop =
listData.get(viewType).getDiliveryfee();
homebuyer.Shop_name = listData.get(viewType).getShopname();
homebuyer.minimum_order = listData.get(viewType).getMinorder();
//profession=items.get(i).getName();
// Toast.makeText(getActivity(),phn,Toast.LENGTH_SHORT).show();
all_and_cetegory_items items = new all_and_cetegory_items();
Bundle b = new Bundle();
b.putString("phone",homebuyer.phone_number_shop);
items.setArguments(b);
FragmentTransaction fragmentTransaction =
((AppCompatActivity)context).getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, items);
fragmentTransaction.addToBackStack(null).commit();
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name.setText(listData.get(position).getShopname());
//
Picasso.with(context).load(listData.get(position)
.getShopimage()).into(holder.shopimage);
Glide.with(context).load(listData.get(position).getShopimage())
.into(holder.shopimage);
holder.dilivery.setText("Rs "+listData.get(position).getDiliveryfee()+"
Delivery fee");
holder.minorder.setText("Rs "+listData.get(position).getMinorder()+" minimum");
holder.items.setText(listData.get(position).getShopmessage());
holder.time.setText("Service Available
"+listData.get(position).getStartingtime()+" to
"+listData.get(position).getEndingtime());
Log.i("inadapter","calling time"+listData.get(position).getShopname());
}
#Override
public int getItemCount() {
return listData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView dilivery;
TextView items;
TextView minorder;
TextView time;
ImageView shopimage;
public ViewHolder(#NonNull View v) {
super(v);
name = (TextView) v.findViewById(R.id.name_item);
dilivery = (TextView) v.findViewById(R.id.price_item);
minorder = (TextView) v.findViewById(R.id.minumum_order);
items=(TextView)v.findViewById(R.id.items_all);
time=(TextView)v.findViewById(R.id.shoptimming);
shopimage=(ImageView) v.findViewById(R.id.image_items);
}
}
}
In error it is saying that the Adapter for RecylerView is not attached. So, try to add adapter to the layout using:
recyclerView.setAdapter(categoryAdapter);
I am assuming homebuyer_adapter_recycler is your adapter.
According to that, you haven't really set your adapter as the logcat is specifying.
Add the below code instead of allitemsgrid.setAdapter(r);
allitemsgrid.setAdapter(homebuyer_adapter_recycler);
If my assumption or suggestion is wrong, it is okay. It is probably because your question is not very clear and does not provide the necessary details. Please provide more details such as the adapter class code and what is allitemsgrid, homebuyer_adapter_recycler and r.

Fetch Data From DB and Display It in a Viewpager In A recyclerview

Before marking as duplicate et al, viewpager from recyclerview is kind of triccky. The code is able to retrieve data from db and display it in a recyclerview with cardview. I want to be able to scroll the images in the viewpager while in the recyclerview as shown in the wireframe below, the dots represent number of images retrieved from DB which should be swipeeable right or left. Imageview seems not to be swipeable.
IMAGE ADAPTER.JAVA
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
List<ImageList>imageLists;
Context context;
public ImageAdapter(List<ImageList> imageLists, Context context) {
this.imageLists = imageLists;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.image_list,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ImageList imageList = imageLists.get(position);
holder.tvname.setText(imageList.getName());
holder.tv2name.setText(imageList.getName2());
String picture = imageList.getImageurl();
String picture2 = imageList.getImage2url();
String picture3 = imageList.getImage3url();
String[] imageUrls = {picture, picture2, picture3};
Picasso.get()
.load(picture)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.resize(0, 200)
.into(holder.img);
}
#Override
public int getItemCount() {
return imageLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tvname, tv2name;
private ImageView img;
public ViewHolder(View itemView) {
super(itemView);
img=(ImageView)itemView.findViewById(R.id.image_view);
tvname=(TextView)itemView.findViewById(R.id.txt_name);
tvname=(TextView)itemView.findViewById(R.id.txt_name2);
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardUseCompatPadding="true"
android:padding="2dp"
android:layout_margin="5dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="200dp"
android:contentDescription="ServerImg"
android:scaleType="fitXY" />
</androidx.cardview.widget.CardView>
<TextView
android:textSize="25sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
android:id="#+id/txt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:textSize="25sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
android:id="#+id/txt_name2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

RecyclerView create views with x amount of rows

I want to create dynamic views with x number of rows for each CardView that gets created. To help illustrate my idea this image shows what I essentially want to do.
For each CardView I want to be able to put any amount of TableRows into the CardView. So one CardView could have 4 rows whereas the next CardView could have 2 rows and so on.
EDIT: Implementation
Essentially this view is replicated several times, I would like to minimise having to write seperate layouts for each CardView with x amount of rows like in the Card Storage implemenation which is more reusable than what I currently have. As I hit the limit here, I have posted a pastebin of the current layout with rows that I have
https://pastebin.com/9RFDGhXv
Layout: Card Storage
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
style="#style/CardStyle">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/MainConstraints" >
<TableRow
android:id="#+id/row_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<TextView
android:id="#+id/card_title"
style="#style/Title"/>
</TableRow>
<TableRow
android:id="#+id/row_two"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#+id/row_one"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<ImageView
android:id="#+id/drawable"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
style="#style/RowDrawableElement"
/>
<TextView
android:id="#+id/percentage_descriptor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="#id/drawable"
android:text="#string/percentage_descriptor"
style="#style/RowTextElement" />
<TextView
android:id="#+id/percentage_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
style="#style/RowTextElement" />
</android.support.constraint.ConstraintLayout>
</TableRow>
<TableRow
android:id="#+id/row_three"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_two"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
style="?android:attr/progressBarStyleHorizontal"
/>
</TableRow>
<TableRow
android:id="#+id/row_four"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_three"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<TextView
android:id="#+id/text_used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
android:id="#+id/text_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
</TableRow>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Adapter
public class StorageAdapter extends RecyclerView.Adapter<StorageAdapter.MyViewHolder> {
private Context mContext;
private List<StorageObjects> mList;
public StorageAdapter(Context context, List<StorageObjects> list) {
this.mContext = context;
this.mList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_storage, parent, false);
return new MyViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
StorageObjects storageObjects = mList.get(position);
long used = storageObjects.getUsed();
long total = storageObjects.getTotal();
holder.mProgress.setMax(0);
holder.mProgress.setProgress(0);
holder.mTitle.setText(storageObjects.getTitle());
MiscUtils.testDrawableIdentifier(mContext.getApplicationContext(), holder.mImageViews, storageObjects.getDrawables());
holder.mPercentage.setText(storageObjects.getPercentage() + mContext.getString(R.string.percentage));
holder.mProgress.setMax((int) (total/100000));
holder.mProgress.setProgress((int) (used/100000));
holder.mUsed.setText(MiscUtils.humanReadableByteSize(used));
holder.mTotal.setText(MiscUtils.humanReadableByteSize(total));
}
#Override
public int getItemCount() {
return mList.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.card_title) TextView mTitle;
#BindViews({R.id.drawable}) List<ImageView> mImageViews;
#BindView(R.id.percentage_text) TextView mPercentage;
#BindView(R.id.progress_bar) ProgressBar mProgress;
#BindView(R.id.text_used) TextView mUsed;
#BindView(R.id.text_total) TextView mTotal;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
Class Storage
public class Storage extends Fragment {
private Unbinder mUnbinder;
private List<StorageObjects> storageList;
private StorageAdapter adapter;
private RecyclerView.LayoutManager mLayoutManager;
#BindArray(R.array.storage_ic_images)
String mDrawables[];
#BindView(R.id.recycler_view)
RecyclerView mRecyclerView;
public Storage() {
// Required empty public constructor
}
public static Storage newInstance() {
return new Storage();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_storage, container, false);
mUnbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
initRecyclerView();
}
#Override
public void onDestroy() {
super.onDestroy();
mUnbinder.unbind();
}
private void initRecyclerView() {
storageList = new ArrayList<>();
adapter = new StorageAdapter(getActivity(), storageList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager = ViewUtils.getLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(2, ViewUtils.dpToPx(
getActivity(), 10), true));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(adapter);
prepareView();
}
#SuppressLint("SetTextI18n")
private void prepareView(){
StorageObjects storage
= new StorageObjects(
getActivity().getString(R.string.int_storage_title),
StorageUtils.internalUsed(),
StorageUtils.internalTotal(),
StorageUtils.internalPercentage(),
mDrawables[0]);
storageList.add(storage);
storage = new StorageObjects (
getActivity().getString(R.string.ext_storage_title),
StorageUtils.externalUsed(getActivity()),
StorageUtils.externalTotal(getActivity()),
StorageUtils.externalPercentage(getActivity()),
mDrawables[1]
);
storageList.add(storage);
adapter.notifyDataSetChanged();
}
}
If number of rows per card view is less then you can inflate edit text and add it to linear layout.
Note : It's a bad practice to add scroll view inside a scroll view

Categories

Resources