I'm trying to sort my RecyclerView with a Spinner. Every item in the List contains 1 ImageView and 2 TextView components. Would be a pleasure if somebody could implement the Spinner to my code, that I can sort those items.
I tried to implement the spinner twice, but needed to rebuild to recycler view without the spinner, because I failed. Don't know how to set up recycler view and spinner together, even with tutorials... I am stuck.
My Item.xml Layout:
<?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="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:background="#color/Green">
<ImageView
android:id="#+id/SupItemIV1"
android:layout_width="150dp"
android:layout_height="75dp"
android:padding="2dp"
android:layout_margin="4dp"/>
<TextView
android:id="#+id/SupItemTV1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="160dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="4dp"
android:text="CREATINE"
android:textColor="#color/Black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/SupItemTV2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:layout_marginTop="30dp"
android:text="amino acid"
android:textColor="#color/GreyDark"
android:textSize="15sp"
android:textStyle="bold"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
My MainActivity (Here Supplements.java class):
package com.example.etigym;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class Supplements 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_supplements);
ArrayList<SupplementsItem> supplementsList = new ArrayList<>();
supplementsList.add(new SupplementsItem(R.drawable.creatine, "CREATINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.glutamine, "GLUTAMINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.leucine, "LEUCINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.valine, "VALINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.isoleucine, "ISOLEUCINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.alanine, "ALANINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.arginine, "ARGININE", "amino acid"));
mRecyclerView = findViewById(R.id.Supplements_RV);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new SupplementsAdapter(supplementsList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
ViewCompat.setNestedScrollingEnabled(mRecyclerView, false);
}
}
My Supplements Layout from the Supplements.java class:
<?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=".Supplements">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/Supplements_RV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:background="#color/GreyDark"
android:scrollbars="vertical"/>
</RelativeLayout>
My Adapter:
public class SupplementsAdapter extends RecyclerView.Adapter<SupplementsAdapter.SupplementsViewHolder> {
private ArrayList<SupplementsItem> mSupplementsList;
public static class SupplementsViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public SupplementsViewHolder(#NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.SupItemIV1);
mTextView1 = itemView.findViewById(R.id.SupItemTV1);
mTextView2 = itemView.findViewById(R.id.SupItemTV2);
}
}
public SupplementsAdapter(ArrayList<SupplementsItem> supplementsList){
mSupplementsList = supplementsList;
}
#NonNull
#Override
public SupplementsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.supplements_item, parent, false);
SupplementsViewHolder svh = new SupplementsViewHolder(v);
return svh;
}
#Override
public void onBindViewHolder(#NonNull SupplementsViewHolder holder, int position) {
SupplementsItem currentSupplementsItem = mSupplementsList.get(position);
holder.mImageView.setImageResource(currentSupplementsItem.getImageResource());
holder.mTextView1.setText(currentSupplementsItem.getText1());
holder.mTextView2.setText(currentSupplementsItem.getText2());
}
#Override
public int getItemCount() {
return mSupplementsList.size();
}
}
SupplementsItem.java:
package com.example.etigym;
public class SupplementsItem {
private int mImageResource;
private String mText1;
private String mText2;
public SupplementsItem(int imageResource, String text1, String text2){
mImageResource = imageResource;
mText1 = text1;
mText2 = text2;
}
public int getImageResource(){
return mImageResource;
}
public String getText1(){
return mText1;
}
public String getText2(){
return mText2;
}
}
Afterwards we should have a List which we can sort by categories.
First you have to know how to sort the items on the list according to your needs, to do that you have to create a class that implements Comparator usually you want to do this class(es) within your Model Class SupplementsItem, this is how it could look your SupplementsItem, note that I added an extra property expiryDate, the idea is that you understand how to use the comparator to sort your list.
public class SupplementsItem {
private int itemImage;
private String item;
private String category;
private long expiryDate;
public SupplementsItem(int itemImage, String item, String category, long expiryDate) {
this.itemImage = itemImage;
this.item = item;
this.category = category;
this.expiryDate = expiryDate;
}
public int getItemImage() {
return itemImage;
}
public void setItemImage(int itemImage) {
this.itemImage = itemImage;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public long getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(long expiryDate) {
this.expiryDate = expiryDate;
}
// This will sort your list ascending by category
public static class CategoryComparatorUp implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return o1.getCategory().compareToIgnoreCase(o2.getCategory());
}
}
// This will sort your list descending by category
public static class CategoryComparatorDown implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return o2.getCategory().compareToIgnoreCase(o1.getCategory());
}
}
// This will sort your list ascending by expiration date
public static class ExpiryComparatorUp implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return Long.compare(o1.getExpiryDate(), o2.getExpiryDate());
}
}
// This will sort your list descending by expiration date
public static class ExpiryComparatorDown implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return Long.compare(o2.getExpiryDate(), o1.getExpiryDate());
}
}
}
I have placed 4 comparators but you really need only one by category, or make a more complex comparator.
For example if you want to sort by Expiration date descending you want to use ExpiryComparatorUp and then Collections.reverse(), like this you can use only one comparator by property in your model.
To use it after you populate your list, you call:
Collections.sort(supplementsList, new SupplementsItem.CategoryComparatorDown());
followed by:
mAdapter.notifyDataSetChanged();
or you can create a method for each type of sorting you want to do, i.e.:
private void sortByCategoryDown() {
Collections.sort(supplementsList, new SupplementsItem.CategoryComparatorDown());
mAdapter.notifyDataSetChanged();
}
and then in your onItemSelected of your spinner just call sortByCategoryDown()
From here you only need to work in your spinner logic. Let me know of your doubts in the comments.
I modified your class with the idea of giving you an idea on how to do the Comparator thingy, but you don't need to make it like that.
Related
I have multiple checkboxes (switches in my case), in a nested recycler view. It looks like the following :
I want to be able to retrieve all switch states on this screen when the user goes back and be able to identify which one’s are set to true. For example, I’m looking to obtain something in a similar format to this:
[Item 0, Sub Item 1, TRUE], [Item 0, Sub Item 2, TRUE], [Item 1, Sub Item 0, TRUE] , etc.
My issue is that I’m not exactly sure how to store these switch states. I'm not sure how to get the specific switch values here when they're placed in a nested recycler view.
Here is the code I'm following:
MainActivity
package com.example.recycledviewpoolexample;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rvItem = findViewById(R.id.rv_item);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
ItemAdapter itemAdapter = new ItemAdapter(buildItemList());
rvItem.setAdapter(itemAdapter);
rvItem.setLayoutManager(layoutManager);
}
private List<Item> buildItemList() {
List<Item> itemList = new ArrayList<>();
for (int i=0; i<10; i++) {
Item item = new Item("Item "+i, buildSubItemList());
itemList.add(item);
}
return itemList;
}
private List<SubItem> buildSubItemList() {
List<SubItem> subItemList = new ArrayList<>();
for (int i=0; i<3; i++) {
SubItem subItem = new SubItem("Sub Item "+i, false);
subItemList.add(subItem);
}
return subItemList;
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
/*if Checkboxes are true, store/display them in the logs
EXAMPLE OUTPUT:
Item (String)
SubItem (String)
*/
}
}
Item.java
public class Item {
private String itemTitle;
private List<SubItem> subItemList;
public Item(String itemTitle, List<SubItem> subItemList) {
this.itemTitle = itemTitle;
this.subItemList = subItemList;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public List<SubItem> getSubItemList() {
return subItemList;
}
public void setSubItemList(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
}
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
private List<Item> itemList;
ItemAdapter(List<Item> itemList) {
this.itemList = itemList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_item, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i) {
Item item = itemList.get(i);
itemViewHolder.tvItemTitle.setText(item.getItemTitle());
// Create layout manager with initial prefetch item count
LinearLayoutManager layoutManager = new LinearLayoutManager(
itemViewHolder.rvSubItem.getContext(),
LinearLayoutManager.VERTICAL,
false
);
layoutManager.setInitialPrefetchItemCount(item.getSubItemList().size());
// Create sub item view adapter
SubItemAdapter subItemAdapter = new SubItemAdapter(item.getSubItemList());
itemViewHolder.rvSubItem.setLayoutManager(layoutManager);
itemViewHolder.rvSubItem.setAdapter(subItemAdapter);
itemViewHolder.rvSubItem.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
return itemList.size();
}
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);
}
}
}
SubItem.java
package com.example.recycledviewpoolexample;
public class SubItem {
private int subItemImage;
private String subItemTitle;
private boolean checkbox;
public SubItem(String subItemTitle, boolean checkbox) {
this.subItemTitle = subItemTitle;
this.checkbox = checkbox;
}
public int getSubItemImage() {
return subItemImage;
}
public void setSubItemImage(int subItemImage) {
this.subItemImage = subItemImage;
}
public String getSubItemTitle() {
return subItemTitle;
}
public void setSubItemTitle(String subItemTitle) {
this.subItemTitle = subItemTitle;
}
public boolean isSelected() {
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox = checkbox;
}
}
SubItemAdapter.java
public class SubItemAdapter extends RecyclerView.Adapter<SubItemAdapter.SubItemViewHolder> {
private List<SubItem> subItemList;
SubItemAdapter(List<SubItem> subItemList) {
this.subItemList = subItemList;
}
#NonNull
#Override
public SubItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_sub_item, viewGroup, false);
return new SubItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SubItemViewHolder subItemViewHolder, int i) {
final SubItem subItem = subItemList.get(i);
subItemViewHolder.tvSubItemTitle.setText(subItem.getSubItemTitle());
subItemViewHolder.checkBox.setOnCheckedChangeListener(null);
subItemViewHolder.checkBox.setChecked(subItem.isSelected());
subItemViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
subItem.setCheckbox(isChecked);
}
});
}
#Override
public int getItemCount() {
return subItemList.size();
}
class SubItemViewHolder extends RecyclerView.ViewHolder {
TextView tvSubItemTitle;
Switch checkBox;
SubItemViewHolder(View itemView) {
super(itemView);
tvSubItemTitle = itemView.findViewById(R.id.tv_sub_item_title);
checkBox = itemView.findViewById(R.id.switch1);
}
}
}
layout_sub_item.xml
<?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">
<ImageView
android:id="#+id/img_sub_item"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#color/colorPrimaryDark"
android:src="#drawable/ic_launcher_foreground"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/img_sub_item"
android:padding="12dp"
android:orientation="vertical">
<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"/>
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
layout_item.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.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"/>
<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>
Any help would be appreciated. Thanks!
I am using a card view with a recyclerView.The problem I'm having is that the cards are not displaying the images and the text that is supposed to be displayed, all I get is empty cards. any way I could fix this or am I doing something wrong?
avctivitymain xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="8dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
cardsport xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="120dp"
android:layout_height="190dp"
android:id="#+id/car_lay"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:cardview="http://schemas.android.com/tools"
android:layout_margin="5dp"
app:cardCornerRadius="4dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/sport_image"
android:layout_width="match_parent"
android:layout_height="160dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/sport_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="14sp"
android:gravity="center"
android:text="frgrggr"
android:textColor="#2d2d2d"/>
</LinearLayout>
</android.support.v7.widget.CardView>
recyclerview adapter class
import java.util.List;
public class Recycler_view extends RecyclerView.Adapter<Recycler_view.myViewHolder>
{
private Context mContext;
private List<card> mData;
public Recycler_view(Context mContext, List<card> mData)
{
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View v;
LayoutInflater mflate = LayoutInflater.from(mContext);
v = mflate.inflate(R.layout.card_sport,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position)
{
holder.sport_txt.setText(mData.get(position).getType_sport());
holder.image_view.setImageResource(mData.get(position).getImages());
}
#Override
public int getItemCount()
{
return mData.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder
{
TextView sport_txt;
ImageView image_view;
CardView cv;
public myViewHolder(View itemView)
{
super(itemView);
sport_txt = itemView.findViewById(R.id.sport_title);
image_view = itemView.findViewById(R.id.sport_image);
cv = itemView.findViewById(R.id.car_lay);
}
}
}
Main activity java class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
List<card> card_sport;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
card_sport = new ArrayList<>();
// ADDING DATA TO THE CARD ARRAYLIST
card_sport.add(new card("soccer",R.drawable.soccer));
card_sport.add(new card("Cage Fighting",R.drawable.cagef));
card_sport.add(new card("Cricket",R.drawable.cricket));
card_sport.add(new card("WaterPolo",R.drawable.polo));
card_sport.add(new card("Running",R.drawable.runman));
card_sport.add(new card("Swimming",R.drawable.swim));
card_sport.add(new card("Rugby",R.drawable.rugby));
RecyclerView rv = findViewById(R.id.recyclerview);
Recycler_view re_adapter = new Recycler_view(this, card_sport);
rv.setLayoutManager(new GridLayoutManager(this,2));
rv.setAdapter(re_adapter);
}
}
card java class for getters and setters
package com.example.dalian.cool_jungle;
public class card
{
private String type_sport;
private int images;
public card()
{
}
public card(String type_sport,int images)
{
type_sport= type_sport;
images = images;
}
public String getType_sport()
{
return type_sport;
}
public int getImages()
{
return images;
}
public void setType_sport()
{
type_sport =type_sport;
}
public void setImages()
{
images = images;
}
}
log
line 17
line 47
after a taken "this" out my card class it just shows blank cards
Your all above code are fine. There will no problem if you made your card object correctly. That may be like:
public class card {
private String type_sport;
private int image;
public card(String type_sport, int image) {
this.type_sport = type_sport;
this.image = image;
}
public String getType_sport() {
return type_sport;
}
public void setType_sport(String type_sport) {
this.type_sport = type_sport;
}
public int getImages() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
You don't need to pass the context in, you can get it from the parent viewgroup. You also don't need to make the view holder a static class, that might help.
I'm attempting to create a custom adapter to display information from an ArrayList in a list view, but it seems to be rejecting an ArrayList, instead asking for just an array. Here is my faulty code:
ArrayList
public ArrayList<Ing> IngList = new ArrayList<>();
public ArrayList<Ing> get(){
return this.IngList;
}
Object Class
public class Ing {
int init;
double value;
String name;
String unit;
String quantity;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public double getValue(){ return value; }
public void setValue(double value){ this.value = value; }
public int getInit(){ return init; }
public void setInit(int init){ this.init = init; }
public String getUnit(){ return unit; }
public void setUnit(String unit){ this.unit = unit; }
public String getQuantity(){ return quantity; }
public void setQuantity(String quantity){ this.quantity = quantity; }
Ing(String name, double value, int init, String unit, String quantity) {
this.name = name;
this.value = value;
this.init = init;
this.unit = unit;
this.quantity = quantity;
}
}
ListAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
private Ing[] values = null;
public static Kitchen kitchen = new Kitchen();
public ListAdapter(Context context, int textViewResourceId, Ing[] values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
public int getCount(){
return values.length;
}
public Ing getItem(int position){
return values[position];
}
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
TextView unit = (TextView) convertView.findViewById(R.id.unit);
name.setText(kitchen.IngList.get(position).getName());
value.setText(kitchen.IngList.get(position).getQuantity());
unit.setText(kitchen.IngList.get(position).getUnit());
return convertView;
}
}
Assigning adapter
final ListAdapter adapter = new ListAdapter(getContext(),
R.layout.row_layout, IngList);
//error is in line above
final ListView listView = (ListView) root.findViewById(R.id.list);
listView.setAdapter(adapter);
row layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:ellipsize="end"
android:maxLines="1"
android:layout_marginBottom="2dp"
android:layout_marginLeft="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/value"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:maxLines="1"
android:layout_toEndOf="#+id/name"
android:layout_toRightOf="#+id/name"
android:text="Value"
android:layout_marginLeft="50dp"
android:layout_marginBottom="2dp"
android:ellipsize="end"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/unit"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:maxLines="1"
android:layout_toEndOf="#+id/value"
android:layout_toRightOf="#+id/value"
android:text="Unit"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:ellipsize="end"/>
Sorry if I posted more than I needed to. I also apologize in advance for being kind of dumb when it comes to organizing code. Thanks a million to anyone who can find out what's wrong here.
Your Modified ListAdapter
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
private ArrayList<Ing> values = new ArrayList<>();
public static Kitchen kitchen = new Kitchen();
public ListAdapter(Context context, int textViewResourceId, ArrayList<Ing> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
public int getCount(){
return values.size();
}
public Ing getItem(int position){
return values.get(position);
}
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
TextView unit = (TextView) convertView.findViewById(R.id.unit);
name.setText(kitchen.IngList.get(position).getName());
value.setText(kitchen.IngList.get(position).getQuantity());
unit.setText(kitchen.IngList.get(position).getUnit());
return convertView;
}
}
I also don't understand why you have used kitchen.IngList for getting the ArrayList for populating your list. You can use values instead of kitchen.IngList
Like #mark-keen and #mike-m have say, your adapter constructor is expecting Array but you giving it an ArrayList.
You create the adapter with:
public ArrayList<Ing> IngList = new ArrayList<>();
...
final ListAdapter adapter = new ListAdapter(getContext(), R.layout.row_layout, IngList);
But your Adapter constructor is only accepting Array:
public class ListAdapter extends ArrayAdapter<Ing> {
...
private Ing[] values = null;
public ListAdapter(Context context, int textViewResourceId, Ing[] values) {
...
}
}
So, you need to change your constructor to accept the ArrayList as its parameter. Something like this:
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
// don't need to create object for values
// because it depends on the parameter value.
private ArrayList<Ing> values;
...
public ListAdapter(Context context, int textViewResourceId, ArrayList<Ing> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
...
}
I've explored many ways to achieve this. But I'm much confused now. I tried many Githubs libraries but got confused. Also tried this but I don't think it allows a textview to be shown in expanded view: http://bignerdranch.github.io/expandable-recycler-view/
WHAT I WANT: A simple Recyclerview fetching some text from server for different items. On each item click, a layout or view should be expanded and TextView should become visible with respective fetched text from the server.
I have a simple RecyclerView with code following:
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<List> android_versions;
private Context context;
int i =0;
public DataAdapter(Context context,ArrayList<List> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_android;
public ViewHolder(View view) {
super(view);
tv_android = (TextView)view.findViewById(R.id.tv_android);
}
}
List.java (Some functions aren't being used as of now)
public class List {
private String android_version_name;
private String descr;
private int android_image_url;
private String android_image_url1;
public String getAndroid_version_name() {
return android_version_name;
}
public String getDescr(){ return descr;}
public void setDescr(String descr) {
this.descr = descr;
}
public void setAndroid_version_name(String android_version_name) {
this.android_version_name = android_version_name;
}
public int getAndroid_image_url() {
return android_image_url;
}
public String getAndroid_image_url1() {
return android_image_url1;
}
public void setAndroid_image_url(int android_image_url) {
this.android_image_url = android_image_url;
}
public void setAndroid_image_url1(String android_image_url1) {
this.android_image_url1 = android_image_url1;
}
}
row_layout.xml
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
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_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp"
android:background="#drawable/custom_bg"
android:clickable="true"
android:translationZ="3dp"
android:elevation="1dp"
android:focusable="true">
<RelativeLayout
android:layout_marginLeft="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/custom_bg">
<TextView
android:layout_marginTop="10dp"
android:textSize="20sp"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_android"
android:textStyle="normal"
android:layout_centerVertical="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Work.java (It's a fragment)
String[] sublist={
"English",
"Hindi"
};
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
rcl = (RecyclerView) getActivity().findViewById(R.id.homeworklist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rcl.setLayoutManager(layoutManager);
dataAdapter = new DataAdapter(getActivity(), new ArrayList<>(prepareData()));
rcl.setAdapter(dataAdapter);
}
public ArrayList prepareData(){
ArrayList android_version = new ArrayList<>();
for(int i=0;i<sublist.length;i++){
List androidVersion = new List();
androidVersion.setAndroid_version_name(sublist[i]);
android_version.add(androidVersion);
break;
}
return android_version;
}
I have tried many ways to add recyclerview inside a fragment. I'm new for android. My android have 5 fragments one of these fragment I need to add a recyclerview. here is my code
notification_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notification_item_root"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical|left"
android:orientation="horizontal"
android:paddingLeft="16dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/notification_item_img"
android:layout_width="36dp"
android:layout_height="36dp"
android:src="#android:drawable/ic_input_get" />
<TextView
android:id="#+id/notification_item_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:paddingLeft="8dp"
android:text="Test Testre" />
</LinearLayout>
notification_Fragment.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:orientation="vertical">
<android.support.v7.app.AlertController.RecycleListView
android:id="#+id/notification_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
NotificationItem.java
public class NotificationItem {
private String title;
private int imageResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageResId() {
return imageResId;
}
public void setImageResId(int imageResId) {
this.imageResId = imageResId;
}
}
NotificationData.java
public class NotificationData {
private static final String[] textItem = {"pathum", "sai", "charu"};
private static final int[] imgItem = {android.R.drawable.ic_popup_reminder, android.R.drawable.ic_menu_add, android.R.drawable.ic_menu_delete};
public static List<NotificationItem> getListData() {
List<NotificationItem> data = new ArrayList<>();
for (int x = 0; x < 4; x++) {
for (int i = 0; i < textItem.length && i < imgItem.length; i++) {
NotificationItem item = new NotificationItem();
item.setImageResId(imgItem[i]);
item.setTitle(textItem[i]);
data.add(item);
}
}
return data;
}
}
NotificationAdapter.java
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationHolder> {
private List<NotificationItem> listData;
private LayoutInflater inflater;
public NotificationAdapter(List<NotificationItem> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public NotificationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.notification_item,parent,false);
return new NotificationHolder(view);
}
#Override
public void onBindViewHolder(NotificationHolder holder, int position) {
NotificationItem item = listData.get(position);
holder.title.setText(item.getTitle());
holder.icon.setImageResource(item.getImageResId());
}
#Override
public int getItemCount() {
return listData.size();
}
class NotificationHolder extends RecyclerView.ViewHolder {
private TextView title;
private CircleImageView icon;
private View container;
public NotificationHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.notification_item_text);
icon = (CircleImageView) itemView.findViewById(R.id.notification_item_img);
container = itemView.findViewById(R.id.notification_item_root);
}
}
}
NotificationFragment.java
public class NotificationFragment extends Fragment {
RecyclerView recyclerView;
NotificationAdapter notificationAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.notification_fragment, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.notification_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
notificationAdapter = new NotificationAdapter(NotificationData.getListData(),this);
recyclerView.setAdapter(notificationAdapter);
return rootView;
}
}
I was unable to make it right in NotificationFragment.java and NotificationAdapter.java please help me guys.
You are using wrong class for RecyclerView, instead of AlertController.RecyclerListView use this:
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Here are some more informations:
RecyclerView
1) first add dependency to your app level gradle file then sync your project
compile 'com.android.support:recyclerview-v7:23.4.0'
2) go to your Layout file (eg: activity_main.xml) add recyclerview tag inside your base layout
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.examples.rehan.excluzo.Fragments.OneFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
3) create a class model.java and paste your code.
public class model{
private String name, gender;
public model() {
}
public model(String name, String gender) {
this.name= name;
this.gender= gender;
}
public String getGender() {
return gender;
}
public void setGender(String gneder) {
this.gender= gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
}
4)create xml file in your layout folder item_layout.xml and paste this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp" >
<TextView
android:id="#+id/name"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/gender"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
5)your need to create adapter to add child views to your listview. so create a file testAdapter.java file and paste this code.
here in list view i will be having only 2 items(eg : Name and gender)
public class testAdapter extends RecyclerView.Adapter<testAdapter.MyViewHolder> {
private List<model> productList;
Context context;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
model product = productList.get(position);
holder.name.setText(product.getName());
holder.gender.setText(product.getGender());
}
#Override
public int getItemCount() {
return productList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,gender;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
gender = (TextView) view.findViewById(R.id.gender);
}
}
public testAdapter(List<model> productList, Context context) {
this.productList = productList;
this.context = context;
}
}
6) now goto your MainActivity.java and paste this code
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<modle> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private testAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new testAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
preparedata();
}
private void preparedata() {
model movie = new model("XXX", "Male");
movieList.add(movie);
//add the items according to your wish
//name,gender
//here i have added all items with same name and gender. you can change it
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
model movie = new model("XXX", "Male");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
}
Hope this helps :)