I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}
Related
When I add an item by button Scan Now, the public double sumCost value incrementes by the cost value in the AddItem method and then TextView(android:id="#+id/SumText") assigns this value. And How to decrease sumCost by the number that is in cost and set new text in TextView when pressing the Delete button? Thanks for any help
enter image description here
My full code:
MainActivity:
package com.example.testfirst;
...
public class MainActivity extends AppCompatActivity {
TextView sumText;
Button buttonAdd;
List<Contact> contacts = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
buttonAdd = (Button) findViewById(R.id.scanBtn);
sumText = (TextView) findViewById(R.id.SumText);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddItem("Tom", 2.45);
sumText.setText(Double.toString(sumCost));
}
});
}
public void AddItem(String name, double cost){
sumCost += cost;
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
contacts.add(new Contact(name,Double.toString(cost)));
}
public double sumCost = 0;
}
Contact(Model class):
...
public class Contact {
private String mName;
private String mCost;
public Contact(String name, String cost) {
mName = name;
mCost = cost;
}
public String getName() {
return mName;
}
public String getCost() {
return mCost;
}
}
ContactsAdapter:
...
public class ContactsAdapter extends RecyclerView.Adapter<ViewHolder>{
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
return new ViewHolder(contactView).linkAdapter(this);
}
///////////////
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Contact contact = mContacts.get(position);
TextView textViewId = holder.nameId;
textViewId.setText(contact.getName());
TextView textViewCost = holder.nameCost;
textViewCost.setText(contact.getCost());
}
#Override
public int getItemCount() {
return mContacts.size();
}
List<Contact> mContacts;
public ContactsAdapter(List<Contact> contacts) {
mContacts = contacts;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ContactsAdapter adapter;
public TextView nameId;
public TextView nameCost;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameId = (TextView) itemView.findViewById(R.id.text);
nameCost = (TextView) itemView.findViewById(R.id.textCost);
itemView.findViewById(R.id.delete).setOnClickListener(view -> {
adapter.mContacts.remove(getAdapterPosition());
adapter.notifyItemRemoved(getAdapterPosition());
});
}
public ViewHolder linkAdapter(ContactsAdapter adapter){
this.adapter = adapter;
return this;
}
}
item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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_margin="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
app:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/app_name"
android:textSize="20sp" />
<TextView
android:id="#+id/textCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:text="#string/app_name"
android:textSize="20sp" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Delete" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout 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=".MainActivity"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/SumText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="0.00"
android:textSize="30sp"/>
<Button
android:id="#+id/scanBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan now"
android:textSize="30sp"
android:layout_gravity="center_horizontal"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
One easy way to do that would be do add a "Decrementer" interface in the adapter that it can call to decrement the total cost, like this:
// Define the interface
public interface Decrementer {
void onDelete(double cost);
}
// Define an instance of the interface to hold
private final Decrementer mDecrementer;
// Pass in a decrementer at construction
public ContactsAdapter(List<Contact> contacts, Decrementer decr) {
mContacts = contacts;
mDecrementer = decr;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// get views and such ...
// Call the decrementer method when the button is clicked
// Could set this in onBindViewHolder, or pass the decrementer
// into the ViewHolder itself and use it there.
deleteButton.setOnClickListener(view -> {
int pos = holder.getAdapterPosition();
Contact c = mContacts.get(pos);
// add getCostAmount to return a double, or better yet, just
// store it as a Double instead of a string in Contact
mDecrementer.onDelete(c.getCostAmount());
mContacts.remove(pos);
notifyItemRemoved(pos);
});
}
and you would define the Decrementer when you create the adapter so it can access the Activity class members, like this:
ContactsAdapter adapter = new ContactsAdapter(contacts, new ContactsAdapter.Decrementer() {
#Override
public void onDelete(double cost) {
sumCost -= cost;
// change activity TextViews and such here too
sumText.setText(Double.toString(sumCost));
}
});
Side note: you don't need to create a whole new adapter every time you add an item, just add it to the contacts array and call an appropriate notifyDataSetChanged method on the existing adapter.
private ContactsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
//...
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
public void AddItem(String name, double cost){
sumCost += cost;
contacts.add(new Contact(name,Double.toString(cost)));
adapter.notifyDataSetChanged(); // or a less expensive notify call
}
I am developing an app in which I am showing users data in a recyclerview. I have used a library which shows preview of a url.
My Problem
Each user has video1, video2, and video3 nodes and I want to display the data of each user 3 times i.e. in the first itemView I want to display video1, in the 2nd video2, and in the 3rd video3. So each user will have 3 itemViews. Below is my code. Please do ask if you need any clarification. Thanks in advance
[![Database Struction][1]][1]
[1]: https://i.stack.imgur.com/XJQqt.png
Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<ModelClass> modelClass = new ArrayList<>();
public MyAdapter(Context context, ArrayList<ModelClass> modelClass) {
this.context = context;
this.modelClass = modelClass;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.gig_display_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.urlEmbeddedView.setURL(modelClass.get(position).getVideo1(), new URLEmbeddedView.OnLoadURLListener() {
#Override
public void onLoadURLCompleted(URLEmbeddedData data) {
holder.urlEmbeddedView.title(data.getTitle());
holder.urlEmbeddedView.description(data.getDescription());
holder.urlEmbeddedView.host(data.getHost());
holder.urlEmbeddedView.thumbnail(data.getThumbnailURL());
holder.urlEmbeddedView.favor(data.getFavorURL());
}
});
}
#Override
public int getItemCount() {
return modelClass.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
URLEmbeddedView urlEmbeddedView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
urlEmbeddedView = itemView.findViewById(R.id.urlView);
}
}
}
Model Class
public class ModelClass {
public String name, video1, video2, video3, videos;
int showVideoCount = 1;
int lifeTimeClicks = 0;
int lifeTimeClicksOnProfile = 0;
int dailyClicksOnProfile = 0;
int dailyClicksByYou = 0;
public ModelClass(String name, String video1, String video2, String video3) {
this.name = name;
this.video1 = video1;
this.video2 = video2;
this.video3 = video3;
}
public ModelClass() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideo1() {
return video1;
}
public void setVideo1(String video1) {
this.video1 = video1;
}
public String getVideo2() {
return video2;
}
public void setVideo2(String video2) {
this.video2 = video2;
}
public String getVideo3() {
return video3;
}
public void setVideo3(String video3) {
this.video3 = video3;
}
HomeFragment
dRef.addListenerForSingleValueEvent(new ValueEventListener() { // singleValueEvent will only call the firebase database once
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list = new ArrayList<ModelClass>();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
ModelClass modelClass = dataSnapshot.getValue(ModelClass.class);
list.add(modelClass);
Collections.shuffle(list); // This will shuffle the links
}
MyAdapter adapter = new MyAdapter(getActivity(), list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Sir Use Nested Recyclerview, Inside your main Item view in xml use another recyclerview.
e.g:
MainAcitivty.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.constraint.ConstraintLayout>
FirstItem.xml:
<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.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#f3f3f3"
app:cardElevation="8dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12sp"
android:textSize="18sp"
android:text="Item Title"/>
//recycler for video
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_sub_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
SubItem.xml (for displaying videos) :
<?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">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="12dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tv_sub_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Sub item title"/> //Video
</RelativeLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
you have model and adapter for MainItem already, Now create model and adapter for subitem(for videos), now in onBindViewHolder of the MainItemAdapter, set subItem layout, also initialize in ItemViewHolder in MainItemAdapter.
e.g. something like this
#Override
public void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i) {
LinearLayoutManager layoutManager = new LinearLayoutManager(
itemViewHolder.rvSubItem.getContext(),
LinearLayoutManager.VERTICAL,
false
);
// Create sub item view adapter
SubItemAdapter subItemAdapter = new SubItemAdapter(item.getSubItemList());
itemViewHolder.rvSubItem.setLayoutManager(layoutManager);
itemViewHolder.rvSubItem.setAdapter(subItemAdapter);
itemViewHolder.rvSubItem.setRecycledViewPool(viewPool);
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView tvItemTitle;
private RecyclerView rvSubItem;
ItemViewHolder(View itemView) {
super(itemView);
tvItemTitle = itemView.findViewById(R.id.tv_item_title);
rvSubItem = itemView.findViewById(R.id.rv_sub_item);
}
}
When I try to run the app my recycler view unable to generate the output.
It is unable to load data and there is no error the code.
Below is adapter class
PlayerListAdapter.java
public class PlayerListAdapter extends RecyclerView.Adapter<PlayerListAdapter.FeaturedViewHolder> {
ArrayList<plaerListHelperClass> featuredLocation;
public PlayerListAdapter(ArrayList<plaerListHelperClass> featuredLocation) {
this.featuredLocation = featuredLocation;
}
#NonNull
#Override
public FeaturedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.playerlist,parent,false);
FeaturedViewHolder featuredViewHolder= new FeaturedViewHolder(view);
return featuredViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FeaturedViewHolder holder, int position) {
plaerListHelperClass plaerListHelperClass = featuredLocation.get(position);
String namep= plaerListHelperClass.getPlayerName();
String mailp= plaerListHelperClass.getPlayerEmail();
holder.name.setText(namep);
holder.mail.setText(mailp);
}
#Override
public int getItemCount() {
return featuredLocation.size();
}
public static class FeaturedViewHolder extends RecyclerView.ViewHolder{
TextView name,mail;
public FeaturedViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.playerName);
mail=itemView.findViewById(R.id.pmail);
}
}
mainactivity.java
This is main activity of my code
public class MainActivity extends AppCompatActivity {
RecyclerView featuredRecycler;
RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
featuredRecycler=findViewById(R.id.playerListRecyclerView);
featuredRecycler();
}
private void featuredRecycler() {
featuredRecycler.setHasFixedSize(true);
ArrayList<plaerListHelperClass> featuredLocation = new ArrayList<>();
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
adapter=new PlayerListAdapter(featuredLocation);
featuredRecycler.setAdapter(adapter);
}
Build this helper class to contains the element that is to be send to the recycler view layout
plaerListHelperClass.java
public class plaerListHelperClass {
String playerName;
String playerEmail;
public plaerListHelperClass(String playerName, String playerEmail) {
this.playerName = playerName;
this.playerEmail = playerEmail;
}
public String getPlayerName() {
return playerName;
}
public String getPlayerEmail() {
return playerEmail;
}
}
playerlist.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<TextView
android:id="#+id/playerName"
android:layout_height="wrap_content"
android:textColor="#897668"
android:layout_weight="1.50"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_marginLeft="0dp"/>
<TextView
android:id="#+id/pmail"
android:layout_height="wrap_content"
android:textColor="#897668"
android:layout_below="#+id/name"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
</LinearLayout>
activity_main.xml
<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=".MainActivity"
android:background="#color/white">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/playerListRecyclerView"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Welcome to the Stack Overflow,
your implementation is correct but I guess you forgot to add the Layout Manager for RecyclerView.
so you can do this by adding it in xml or in your java class as :
activity_main.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=".MainActivity"
android:background="#color/white">
<!-- for Linear layout...-->
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/playerListRecyclerView"
tools:listitem="#layout/playerlist"
tools:itemCount="7"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Or,
you can add it in your java class as
private void featuredRecycler() {
featuredRecycler.setHasFixedSize(true);
ArrayList<plaerListHelperClass> featuredLocation = new ArrayList<>();
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
featuredLocation.add(new plaerListHelperClass("Shubham","Shubham#gmail.com"));
adapter=new PlayerListAdapter(featuredLocation);
featuredRecycler.setAdapter(adapter);
featuredRecycler.setLayoutManager(new LinearLayoutManager(this#MainActivity))
}
for more reference you can refer https://www.javatpoint.com/android-recyclerview-list-example
I'm new to Android Studio and coding in general and I am trying to display a custom ListView with an image of a colour and the name of the colour. I have used a custom Adapter to inflate the view with two arrays containing the drawable image colours and string of the names.
The problem I am having - the custom adapter is only displaying the layers from position 1 and onwards. For example, where the first layer should be img_01 and "red" - it is displaying img_02 and "Orange".
I've tried debugging the code and it seems that though the adapter is setting the values for position 0, but I cannot find the reason why it is not displaying (as the others are displaying fine).
The images & names are just placeholders, so an alternative solution that doesn't include both the drawables and names wouldn't be viable,
Thank you in advance
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
int[] images;
String[] colour;
LayoutInflater mInflater;
public CustomAdapter(Context c, int[] i, String[] col) {
this.context = c; //sets the application context that has been passed to the adapter
this.images = i; //sets the images array that has been passed to the adapter
this.colour = col; //sets the colour array that has been passed to the adapter
mInflater = (LayoutInflater.from(context)); //sets the layout inflater from context
}
#Override
public int getCount() { //total number of elements in the array
return images.length;
}
#Override
public Object getItem(int position) { //gets the item using the position
return null;
}
#Override
public long getItemId(int position) { //gets the item position
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { //this is used to update the view
convertView = mInflater.inflate(R.layout.custom_layout, null);
ImageView image = convertView.findViewById(R.id.imageView);
TextView text = convertView.findViewById(R.id.textView);
text.setText(colour[position]);
image.setImageResource(images[position]);
return convertView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView mListView;
int[] images = {R.drawable.img01,
R.drawable.img02,
R.drawable.img03,
R.drawable.img04};
String[] colour = {"Red",
"Orange",
"Yellow",
"Green"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), images, colour);
//passes information of images and application context to the item adapter
mListView.setAdapter(customAdapter);
//sets the adapter to the listview
}
}
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="7dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="9dp"
app:srcCompat="#drawable/img01" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="99dp"
android:layout_marginLeft="99dp"
android:layout_marginTop="36dp"
android:text="colourName" />
</RelativeLayout>
activity_main.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=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try to set the height of the ListView to wrap_content instead of hardcoding it
<ListView
...
android:layout_height="wrap_content"/>
You can do it with RecyclerView.
Create a custom class
public class ExampleItem {
private int mImageResource; //your color image
private String mText1; //your text
public ExampleItem(int imageResource, String text1) {
mImageResource = imageResource;
mText1 = text1;
}
public int getImageResource() {
return mImageResource;
}
public String getText1() {
return mText1;
}
}
Create a XML layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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="4dp"
app:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="2dp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:text="Line 1"
android:textColor="#android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Create a Recycler View Adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView1 = itemView.findViewById(R.id.textView);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
your activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
tools:context="com.example.application.recyclerviewproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:padding="4dp"
android:scrollbars="vertical" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ExampleItem> exampleList = new ArrayList<>();
exampleList.add(new ExampleItem(R.drawable.img01, "Red"));
exampleList.add(new ExampleItem(R.drawable.img02, "Orange"));
exampleList.add(new ExampleItem(R.drawable.img03, "Yellow"));
exampleList.add(new ExampleItem(R.drawable.img04, "Green"));
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
I am having problems in displaying cards dynamically from a recycler view. Here's my code.
CardActivity.java
public class CardActivity extends AppCompatActivity {
CardAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<CardModel> data = new ArrayList<>();
public static String IMGS[] = {
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12540788_486126334923939_641652950626105372_n.jpg?oh=520090fa887ded912ddb7086fc69fc93&oe=57A04969",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/12973436_521081094761796_6679453535369186441_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12191632_465602330309673_5460380145671805117_n.jpg?oh=51811b46395fee6e4bdb5394e6725591&oe=57D35DC3",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/10628472_397420133794560_5446805358922772021_n.jpg?oh=f23ab8761e05b2a50d0d0c9dec4d365b&oe=57DBF1CC",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/10697227_314766035393304_2937143993369666506_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/13133194_10154674163886840_3764712620850385571_n.jpg?oh=252cedf88040188f12ce99c29f3dd47e&oe=57DD7474"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
for (int i = 0; i < IMGS.length; i++) {
CardModel cardModel = new CardModel();
cardModel.setTitle("Card Title: " + i);
cardModel.setDescription("This is a card description");
cardModel.setUrl(IMGS[i]);
data.add(cardModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Cards");
mRecyclerView = (RecyclerView) findViewById(R.id.cards);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CardActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mAdapter = new CardAdapter(CardActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
}
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}
CardModel.java
public class CardModel {
String url,title,description;
public CardModel() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardHolder> {
private LayoutInflater inflater;
Context context;
List<CardModel> data = new ArrayList<>();
public CardAdapter(Context context, List<CardModel> data){
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
#Override
public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_layout,parent,false);
CardHolder cardHolder = new CardHolder(view);
return cardHolder;
}
#Override
public void onBindViewHolder(CardHolder holder, int position) {
holder.cardTitle.setText(data.get(position).getTitle());
holder.cardDescription.setText(data.get(position).getDescription());
Glide.with(context).load(data.get(position).getUrl())
.fitCenter()
.into(holder.cardImage);
}
#Override
public int getItemCount() {
return 0;
}
public static class CardHolder extends RecyclerView.ViewHolder {
ImageView cardImage;
TextView cardTitle;
TextView cardDescription;
public CardHolder(View cardView) {
super(cardView);
cardImage = (ImageView) cardView.findViewById(R.id.card_image);
cardTitle = (TextView) cardView.findViewById(R.id.card_title);
cardDescription = (TextView) cardView.findViewById(R.id.card_description);
}
}
}
activity_card.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.braudy.android.mesasixprofiler.CardActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
card_layout.xml
<?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="match_parent"
android:background="#FFFFFF"
android:padding="10dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#ffffff">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:alpha=".7"
android:id="#+id/card_image"
android:background="#ffff66"
android:src="#drawable/img1"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Braudy"
android:paddingLeft="15dp"
android:textColor="#FFFFFF"
android:background="#707070"
android:alpha=".8"
android:textSize="25sp"
android:id="#+id/card_title"
android:layout_alignBottom="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="This is a description"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:textColor="#A9A9AF"
android:textSize="15sp"
android:id="#+id/card_description"
android:layout_below="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Change this
#Override
public int getItemCount() {
return 0;
}
to
#Override
public int getItemCount() {
return data.size();
}
change here-
#Override
public int getItemCount() {
return data.size();
}
You have to declare how much views you want to inflate in your view.