I am learning to use FastAdapter with Realm. Here is my model and this is how I implement OnClick in a Fragment:
fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<ProductsModel>() {
#Override
public boolean onClick(View v, IAdapter<ProductsModel> adapter, ProductsModel item, int position) {
Toast.makeText(getActivity(), "got it", Toast.LENGTH_SHORT).show();
return false;
}
});
But I don't get the Toast appearing. Can anybody please tell me what am I missing?
Update: Here is my model
public class ProductsModel extends RealmObject implements IItem<ProductsModel, ProductsModel.ViewHolder>{
#PrimaryKey
private String code;
private String name, generic, packSize;
private int quantity, status;
//variables needed for adapter
protected boolean isSelected = false; // defines if the item is selected
#Ignore
protected Object tag;// defines if this item is isSelectable
#Ignore
protected boolean isSelectable = true;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPackSize() {
return packSize;
}
public void setPackSize(String packSize) {
this.packSize = packSize;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getGeneric() {
return generic;
}
public void setGeneric(String generic) {
this.generic = generic;
}
#Override
public Object getTag() {
return tag;
}
#Override
public ProductsModel withTag(Object tag) {
this.tag = tag;
return this;
}
#Override
public boolean isEnabled() {
return false;
}
#Override
public ProductsModel withEnabled(boolean enabled) {
return null;
}
#Override
public boolean isSelected() {
return isSelected;
}
#Override
public ProductsModel withSetSelected(boolean selected) {
return null;
}
#Override
public boolean isSelectable() {
return isSelectable;
}
#Override
public ProductsModel withSelectable(boolean selectable) {
this.isSelectable = selectable;
return this;
}
#Override
public int getType() {
return R.id.pwdsList;
}
#Override
public int getLayoutRes() {
return R.layout.item_product;
}
#Override
public View generateView(Context ctx) {
ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), null, false));
bindView(viewHolder, Collections.EMPTY_LIST);
return viewHolder.itemView;
}
#Override
public View generateView(Context ctx, ViewGroup parent) {
ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false));
bindView(viewHolder, Collections.EMPTY_LIST);
return null;
}
private ViewHolder getViewHolder(View view) {
return new ViewHolder(view);
}
#Override
public ViewHolder getViewHolder(ViewGroup parent) {
return getViewHolder(LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false));
}
#Override
public void bindView(ViewHolder holder, List<Object> payloads) {
holder.name.setText(name + " " + packSize + " (" + quantity + ")");
holder.generic.setText(generic);
holder.itemView.setSelected(isSelected());
}
#Override
public void unbindView(ViewHolder holder) {
holder.name.setText(null);
holder.generic.setText(null);
}
#Override
public boolean equals(int id) {
return false;
}
#Override
public ProductsModel withIdentifier(long identifier) {
return null;
}
#Override
public long getIdentifier() {
return 0;
}
static class ViewHolder extends RecyclerView.ViewHolder{
ATextView name, generic;
public ViewHolder(View itemView) {
super(itemView);
name = (ATextView) itemView.findViewById(R.id.name);
generic = (ATextView) itemView.findViewById(R.id.generic);
}
}
}
Your item is not enabled which results in the click event not being forwarded. Just change your code to return isEnabled=true
#Override
public boolean isEnabled() {
return true;
}
Related
I am using a RecyclerView and an adapter to display the data of an array of Event objects. In RecyclerView, I use a CheckBox for one of the object's parameters. How can I save it?
For the rest I use SharedPreferences, but here I don't know how to apply it in my Activity.
Here's my class Event:
public class Event implements Serializable {
public String Name;
public Long Date;
public String Comment;
public String Type;
public String Notify;
public Boolean IsComplete;
public Boolean IsImportant;
Event()
{
Name = "Событие";
Date = MaterialDatePicker.todayInUtcMilliseconds();
Comment = "Comment";
Type = "Material";
Notify = "Не напоминать";
IsComplete = false;
IsImportant = false;
}
Event(String name, Long date, String comment, String type, String notify, Boolean iscomplete, Boolean isimportant)
{
Name = name;
Date = date;
Comment = comment;
Type = type;
Notify = notify;
IsComplete = iscomplete;
IsImportant = isimportant;
}
public String getName() {
return Name;
}
public Long getDate() {
return Date;
}
public String getComment() {
return Comment;
}
public String getType() {
return Type;
}
public String getNotify() {
return Notify;
}
public Boolean getComplete() {
return IsComplete;
}
public Boolean getImportant() {
return IsImportant;
}
}
And my Recycler View and Adapter:
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private ArrayList<Event> mEventList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public EventViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
TVtitle = itemView.findViewById(R.id.tv1);
TVcomment = itemView.findViewById(R.id.tv2);
CBimportance = itemView.findViewById(R.id.iconImportant);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public EventAdapter(ArrayList<Event> listEvent){
mEventList = listEvent;}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
EventViewHolder evh = new EventViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position) {
final Event item = mEventList.get(position);
holder.TVtitle.setText(item.getName());
holder.TVcomment.setText(item.getComment());
holder.CBimportance.setOnCheckedChangeListener(null);
holder.CBimportance.setChecked(item.getImportant());
holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.IsImportant = b;
if (b){
Log.d(TAG, String.valueOf(position) + " IMPORTANT");
}
else{
Log.d(TAG, String.valueOf(position) + " NON IMPORTANT");
}
}
});
}
#Override
public int getItemCount() {
return mEventList.size();
}
}
For example, for ItemClick and changes saving in my Activity I use onItemClick:
adapterEvent.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
eventsProcess.remove(position);
adapterEvent.notifyItemRemoved(position);
write(getContext(), eventsProcess, PROCESSED_EVENTS);
}
});
public static void write(Context context, ArrayList<Event> events, String Key)
{
Gson gson = new Gson();
String jsonString = gson.toJson(events);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Key, jsonString);
editor.apply();
}
You should be able to do this exactly how you handle the 'OnItemClick'. I made some changes in your adapter to add a new interface OnItemCheckedListener and then handle the checkbox checkedChanged events using this listener. (Instead of just logging it like you did).
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private ArrayList<Event> mEventList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
private OnItemCheckedListener mOnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked (int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener) {
mOnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public EventViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
TVtitle = itemView.findViewById(R.id.tv1);
TVcomment = itemView.findViewById(R.id.tv2);
CBimportance = itemView.findViewById(R.id.iconImportant);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public EventAdapter(ArrayList<Event> listEvent){
mEventList = listEvent;
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
EventViewHolder evh = new EventViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position) {
final Event item = mEventList.get(position);
holder.TVtitle.setText(item.getName());
holder.TVcomment.setText(item.getComment());
holder.CBimportance.setOnCheckedChangeListener(null);
holder.CBimportance.setChecked(item.getImportant());
holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.IsImportant = b;
if (b) {
Log.d(TAG, String.valueOf(position) + " IMPORTANT");
}
else{
Log.d(TAG, String.valueOf(position) + " NON IMPORTANT");
}
mOnItemChecked.onItemChecked(position, b)
}
});
}
#Override
public int getItemCount() {
return mEventList.size();
}
}
Now, From your activity just set the OnItemCheckedListener of the EventAdapter.
adapterEvent.setOnItemCheckedListener(new EventAdapter.OnItemCheckedListener {
#Override
public void onItemChecked (int position, boolean isImportant) {
// TODO:
// whatever you want to do with the isImportant data
}
});
How do i set data in RecylerView using Retrofit.I have tried but i was not able to performed it successfully.
Here is my code:
JSON DATA is :
{
"model": [
{
"id": "1",
"brand_name": "Audi",
"brand_logo": "1495456122.",
},
{
"id": "3",
"brand_name": "BMW",
"brand_logo": "1495451144.",
}
]
}
BrandSelectActivity.java
public class BrandSelectActivity extends AppCompatActivity implements View.OnClickListener {
ProgressDialog pDialog;
Button btn_addVehicle;
BrandListRecyclerAdapter adapter;
RecyclerView recyclerView_brand;
public ImageView carBrandImg;
public TextView carBrandName;
private static String TAG = BrandSelectActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand_select);
carBrandImg = (ImageView)findViewById(R.id.carBrandImg);
carBrandName = (TextView)findViewById(R.id.carBrandName);
recyclerView_brand = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setCancelable(true);
pDialog.setMessage("Please Wait...");
pDialog.show();
ArrayList<BrandModel> brandModelArrayList = new ArrayList<BrandModel>();
BrandListRecyclerAdapter brandAdapter = new BrandListRecyclerAdapter(BrandSelectActivity.this, brandModelArrayList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView_brand.setLayoutManager(mLayoutManager);
recyclerView_brand.setAdapter(brandAdapter);
brandAdapter.setItemClickListener(new BrandListRecyclerAdapter.MyClickListerer() {
#Override
public void onItemClick(int position, View view) {
Intent sosIntent = new Intent(BrandSelectActivity.this, ModelSelectActivity.class);
startActivity(sosIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
callBrandSelect();
}
private void callBrandSelect() {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<BrandSelectResponse> call = apiService.saveBrand("1");
call.enqueue(new Callback<BrandSelectResponse>() {
#Override
public void onResponse(Call<BrandSelectResponse> call, retrofit2.Response<BrandSelectResponse> response) {
BrandSelectResponse br= response.body();
List<BrandSelectResponse.ModelBean> modelList = br.getModel();
modelList.size();
modelList.get(0).getBrand_logo();
modelList.get(0).getBrand_name();
pb.dismiss();
}
#Override
public void onFailure(Call<BrandSelectResponse>call, Throwable t) {
Toast.makeText(BrandSelectActivity.this,"Opps ..!!Failed to
connect to our server.. Try Again later..",Toast.LENGTH_SHORT).show();
Log.e(TAG, t.toString());
}
});
}
#Override
public void onClick(View v) {
}
}
BrandListRecyclerAdapter.java
public class BrandListRecyclerAdapter extends RecyclerView.Adapter<BrandListRecyclerAdapter.MyViewHolder> {
Context mcontext;
List<BrandSelectResponse> brandModelArrayList;
public LayoutInflater inflater;
public static MyClickListerer myClickListerer;
public BrandListRecyclerAdapter(Context context, ArrayList<BrandSelectResponse> brandModelArrayList) {
this.mcontext = context;
this.brandModelArrayList=brandModelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_brand, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BrandSelectResponse current = brandModelArrayList.get(position);
holder.setData((BrandSelectResponse) brandModelArrayList,position);
holder.carBrandName.setText(current.getBrand_name());
holder.carBrandImg.setImageResource(current.getBrand_logo());
}
public interface MyClickListerer {
void onItemClick(int position, View view);
}
public void setItemClickListener(MyClickListerer myClickListerer) {
this.myClickListerer = myClickListerer;
}
#Override
public int getItemCount() {
return brandModelArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView carBrandImg;
public TextView carBrandName;
BrandSelectResponse brandModelArrayList;
LinearLayout current;
int position;
public MyViewHolder(View itemView) {
super(itemView);
carBrandImg = (ImageView) itemView.findViewById(R.id.carBrandImg);
carBrandName = (TextView) itemView.findViewById(R.id.carBrandName);
}
public void setData(BrandSelectResponse current, int position) {
carBrandName.setText(brandModelArrayList.getBrand_name());
carBrandImg.setImageResource(brandModelArrayList.getBrand_logo());
this.position = position;
this.brandModelArrayList = current;
}
#Override
public void onClick(View v) {
myClickListerer.onItemClick(getAdapterPosition(), v);
}
}
}
BrandSelectResponse.java
public class BrandSelectResponse implements Serializable{
private List<ModelBean> model;
public BrandSelectResponse(List<ModelBean> model) {
this.model = model;
}
public List<ModelBean> getModel() {
return model;
}
public void setModel(List<ModelBean> model) {
this.model = model;
}
public static class ModelBean {
private String id;
private String brand_name;
private String brand_logo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_logo() {
return brand_logo;
}
public void setBrand_logo(String brand_logo) {
this.brand_logo = brand_logo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
You give to adapter EMPTY list.
You never add data to brandModelArrayList.
Next time try to look at the logcat, what is the exception and which line is the problem.
I have a recycler view with check box in the each card in the view. I want to unchek all the other checkboxes when i clicks on a particular check box in the view(Condition can be like card contains an odd one etc). How can i do that? My adapter code is below.
public class PlatformAdapter extends RecyclerView.Adapter<PlatformAdapter.ViewHolder> {
ArrayList<Batch> batches;
ArrayList<CourseSlug> courses;
boolean isInstituteStudent;
public void setBatches(ArrayList<Batch> batches) {
this.batches = batches;
notifyDataSetChanged();
}
public void setCourses(ArrayList<CourseSlug> courses) {
this.courses = courses;
notifyDataSetChanged();
}
public ArrayList<CourseSlug> getCourses() {
return courses;
}
public ArrayList<Batch> getBatches() {
return batches;
}
public void setInstituteStudent(boolean instituteStudent) {
isInstituteStudent = instituteStudent;
}
public boolean isInstituteStudent() {
return isInstituteStudent;
}
public PlatformAdapter() {
courses = new ArrayList<>();
batches = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_cell_platform_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if (isInstituteStudent) {
Batch batch = batches.get(position);
holder.enrolment.setText(batch.getName());
holder.selectEnrollment.setChecked(batch.isPreselect());
} else {
final CourseSlug course = courses.get(position);
holder.enrolment.setText(course.getName());
holder.selectEnrollment.setChecked(course.isPreselect());
}
}
#Override
public int getItemCount() {
return isInstituteStudent ? batches.size() : courses.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView enrolment;
CheckBox selectEnrollment;
public ViewHolder(final View itemView) {
super(itemView);
enrolment = (TextView) itemView.findViewById(R.id.tv_entrollment);
selectEnrollment = (CheckBox) itemView.findViewById(R.id.cb_select_entrollment);
selectEnrollment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int index = getLayoutPosition();
if(isInstituteStudent) {
Batch batch = batches.get(index);
batch.setPreselect(b);
} else {
CourseSlug course = courses.get(index);
course.setPreselect(b);
}
}
});
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
}
In my Courseslug class, there is a param called isTrue(); if ,courseSlug.isTrue()==true; then which card's check box is satisfying my condition, it gets checked and other unchecked/checked boxes gets unchecked. This is what i want done.
public class CourseSlug {
String name;
String slug;
boolean preselect;
boolean istrue;
public boolean isTrue() {
return istrue;
}
public void setisTrue(boolean isTrue) {
this.isTrue = istrue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public boolean isPreselect() {
return preselect;
}
public void setPreselect(boolean preselect) {
this.preselect = preselect;
}}
Since the views are not necessarily visible, you need to keep a boolean state variable in your adapter. Toggle the variable when the user clicks the "master" checkbox. Then use this variable in onBindViewHolder() to set the checked state of the checkbox in each row.
I have edited your onBindViewHolder method. Hope this is helpful :)
private SparseArray<SparseBooleanArray> sparseArray = new SparseArray<>();
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final CourseSlug course = courses.get(position);
holder.enrolment.setText(course.getName());
holder.selectEnrollment.setChecked(course.isPreselect());
holder.selectEnrollment.setId(position);
holder.selectEnrollment.setChecked(false);
if (sparseArray.get(holder.selectEnrollment.getId()) != null) {
boolean isChecked = sparseArray.get(holder.selectEnrollment.getId()).get(holder.selectEnrollment.getId());
holder.selectEnrollment.setChecked(isChecked);
}
holder.selectEnrollment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sparseArray.clear();
SparseBooleanArray checkedPosition = new SparseBooleanArray();
checkedPosition.put(v.getId(), true);
sparseArray.put(tagId, checkedPosition);
notifySetDataChanged();
}
});
}
This is my adapter class
public class GenreAdapter extends ExpandableRecyclerViewAdapter<GenreViewHolder, ArtistViewHolder> {
Context context ;
LayoutInflater inflater ;
public GenreAdapter(List<? extends ExpandableGroup> groups,Context context) {
super(groups);
this.context = context ;
inflater = LayoutInflater.from(context);
}
#Override
public GenreViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
//LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item_genre, parent, false);
return new GenreViewHolder(view);
}
#Override
public ArtistViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item_artist, parent, false);
return new ArtistViewHolder(view);
}
#Override
public void onBindChildViewHolder(ArtistViewHolder holder, int flatPosition, ExpandableGroup group,
int childIndex) {
final Artist artist =(Artist) group.getItems().get(childIndex);
holder.setArtistName(artist.getName());
}
#Override
public void onBindGroupViewHolder(GenreViewHolder holder, int flatPosition,
ExpandableGroup group) {
holder.setGenreTitle(group);
}
}
This is my model class
package com.nmn.expandablerecycler.utils;
import android.os.Parcel;
import android.os.Parcelable;
import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup;
import java.util.List;
public class Artist implements Parcelable {
private String name;
private boolean isFavorite;
public Artist(String name, boolean isFavorite) {
this.name = name;
this.isFavorite = isFavorite;
}
protected Artist(Parcel in) {
name = in.readString();
}
public String getName() {
return name;
}
/* public String getTitle()
{
return title ;
}*/
public boolean isFavorite() {
return isFavorite;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Artist)) return false;
Artist artist = (Artist) o;
if (isFavorite() != artist.isFavorite()) return false;
return getName() != null ? getName().equals(artist.getName()) : artist.getName() == null;
}
#Override
public int hashCode() {
int result = getName() != null ? getName().hashCode() : 0;
result = 31 * result + (isFavorite() ? 1 : 0);
return result;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Artist> CREATOR = new Creator<Artist>() {
#Override
public Artist createFromParcel(Parcel in) {
return new Artist(in);
}
#Override
public Artist[] newArray(int size) {
return new Artist[size];
}
};
}
public class Genre extends ExpandableGroup<Artist> {
public Genre(String title, List<Artist> items) {
super(title, items);
}
}
>This are my viewholder classes
public class ArtistViewHolder extends ChildViewHolder {
private TextView artistName;
public ArtistViewHolder(View itemView) {
super(itemView);
artistName = (TextView) itemView.findViewById(R.id.artist_name);
}
public void onBind(Artist artist) {
artistName.setText(artist.getName());
}
public void setArtistName (String name )
{
}
}
public class GenreViewHolder extends GroupViewHolder {
private TextView genreTitle;
public GenreViewHolder(View itemView) {
super(itemView);
genreTitle =(TextView) itemView.findViewById(R.id.genre_title);
}
public void setGenreTitle(ExpandableGroup group) {
genreTitle.setText(group.getTitle());
}
}
>this is the main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Artist>artists = new ArrayList<>();
for (int i = 0 ; i<6 ;i++)
{
artists.add(new Artist("naman",true));
}
ArrayList<Genre> genres = new ArrayList<>();
for (int i = 0 ; i<6 ;i++)
{
genres.add(new Genre("Sufi",artists));
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//instantiate your adapter with the list of genres
GenreAdapter adapter = new GenreAdapter(genres,this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
The text on the artist(child) name is not shown up . Althiugh the parent (genre text ) expands and collapses as well .Let me know how to
show the text of child (artist) item in this expandable recyclerview
Dude this might sound silly, but your setArtistName method is empty. paste this code artistName.setText(artist.getName());
The library documentation has error
public void onBind(Artist artist) {
artistName.setText(artist.getName());
}
public void setArtistName (String name )
{
}
In this snippet just change the name of method from onBind to setArtistName and remove the empty method you created.
I was also implementing com.thoughtbot.expandablerecyclerview. What I did in the same scenario was, in the custom class that is extending ExpandableGroup, I override getItems() and getItemCount() methods and provided the values which I wanted as "child"-expanded state.
I have successfully implemented RecyclerView in my app. The RecyclerView has three items, viz. title (TextView), ImageButton, description(TextView).
The title and ImageButton are always visible while the visibility of the description (set GONE by default) is toggled by clicking the ImageButton.
The problem I have is that when you click the ImageButton in one item and the description becomes visible, when you scroll down or up, the fifth (up or down) item has it description visible even when I didn't click the ImageButton to make it visible.
MY CODES:
book_card.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/book_image"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/book_title"
android:textStyle="bold"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_arrow_name"
android:id="#+id/arrow_button"
android:layout_below="#+id/book_title"
android:layout_centerHorizontal="true"
android:onClick="onArrowClick"
android:padding="5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/arrow_button"
android:visibility="gone"
android:id="#+id/book_descrip"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
BookItem
public class BookItems implements Parcelable, Collection<BookItems> {
private String book_title;
private String book_descrip;
public String getBook_title() {
return book_title;
}
public void setBook_title(String book_title) {
this.book_title = book_title;
}
public String getBook_descrip() {
return book_descrip;
}
public void setBook_descrip(String book_descrip) {
this.book_descrip = book_descrip;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.book_title);
dest.writeString(this.book_descrip);
}
public BookItems() {
}
protected BookItems(Parcel in) {
this.book_title = in.readString();
this.book_descrip = in.readString();
}
public static final Parcelable.Creator<BookItems> CREATOR = new Parcelable.Creator<BookItems>() {
#Override
public BookItems createFromParcel(Parcel source) {
return new BookItems(source);
}
#Override
public BookItems[] newArray(int size) {
return new BookItems[size];
}
};
#Override
public boolean add(BookItems object) {
return false;
}
#Override
public boolean addAll(Collection<? extends BookItems> collection) {
return false;
}
#Override
public void clear() {
}
#Override
public boolean contains(Object object) {
return false;
}
#Override
public boolean containsAll(Collection<?> collection) {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#NonNull
#Override
public Iterator<BookItems> iterator() {
return null;
}
#Override
public boolean remove(Object object) {
return false;
}
#Override
public boolean removeAll(Collection<?> collection) {
return false;
}
#Override
public boolean retainAll(Collection<?> collection) {
return false;
}
#Override
public int size() {
return 0;
}
#NonNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#Override
public <T> T[] toArray(T[] array) {
return null;
}
}
BookAdapter
public class BookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private OnItemClickedListener mItemClickedListener;
//List of books
private List<BookItems> mBookItems;
private int lastPosition = -1;
public BookAdapter(List<BookItems> bookItems, Context context) {
super();
//Getting all books
this.mBookItems = bookItems;
this.mContext = context;
this.mItemClickedListener = null;
}
public void setItemClickedListener (OnItemClickedListener onItemClickedListener) {
this.mItemClickedListener = onItemClickedListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_card, parent, false);
return new CardViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final BookItems bookList = mBookItems.get(position);
((CardViewHolder) holder).bookTitle.setText(Html.fromHtml(bookList.getBook_title()));
((CardViewHolder) holder).bookDescrip.setText(Html.fromHtml(bookList.getBook_descrip()));
((CardViewHolder) holder).bookDescrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickedListener != null) {
mItemClickedListener.onItemClicked(bookList.getBookId(), "Book");
}
}
});
((CardViewHolder) holder).bookTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickedListener != null) {
mItemClickedListener.onItemClicked(bookList.getBookId(), "Book");
}
}
});
setAnimation(holder.itemView, position);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.recycler_anim_up);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount(){
return mBookItems.size();
}
#Override
public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder) {
holder.itemView.clearAnimation();
}
public class CardViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#BindView(R.id.book_title) TextView bookTitle;
#BindView(R.id.book_descrip) TextView bookDescrip;
#BindView(R.id.arrow_button) ImageButton imageButton;
public CardViewHolder (final View bookView) {
super(bookView);
ButterKnife.bind(this, bookView);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == imageButton.getId()) {
int visibility = bookDescrip.getVisibility();
if (visibility == View.VISIBLE) {
bookDescrip.setVisibility(View.GONE);
} else {
bookDescrip.setVisibility(View.VISIBLE);
}
}
}
}
}
Please is there anyway to stop this misbehavour?
I followed Tasos suggestion and this is how it was fixed.
In BookItem I added this:
private boolean descVisible = false;
public boolean isDescVisible() {
return descVisible;
}
public void setDescVisible(boolean descVisible) {
this.descVisible = descVisible;
}
Then in BookAdapter onBindViewHolder, I did this:
if (bookList.isVisible()) {
((CardViewHolder) holder).bookDescrip.setVisibility(View.VISIBLE);
} else {
((CardViewHolder) holder).bookDescrip.setVisibility(View.GONE);
}
((CardViewHolder) holder).imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bookList.isDescVisible()) {
((CardViewHolder) holder).bookDescrip.setVisibility(View.GONE);
bookList.setDescVisible(false);
} else {
((CardViewHolder) holder).bookBody.setVisibility(View.VISIBLE);
bookList.setDescVisible(true);
}
}
});