not getting id of a clicked child item inside RecyclerView item layout - android

I have implemented a RecyclerView inside a ConstraintLayout. I am having one child image element inside the layout. But when I click the child image, it always returns the ConstraintLayout, not the clicked image.
Could you please tell me why this is happening, what is the solution for this ?
I separately did bind listener to image, it is working but not able to get the RecyclerItem object. I need RecyclerItem object for the position to proceed.
I implemented it by binding elements via onBindViewholder method in Adapter. Below are the codes
customAdapter = new GridViewAdapter(recyclerItems, 1, this.getContext().getPackageName(),
new GridViewAdapter.OnItemClickListener(){
#Override
public void onItemClick(RecyclerItem item) {
CommonUtil.addFragment("REP", Constants.CONTAINER_HOME,
new ModifyFragment(), getActivity(), null);
}
}, R.layout.rec_view_item_stock, Constants.V_SPAN_LIST_8);
RecyclerView recyclerView = view.findViewById(R.id.stockListRecView);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new GridLayoutManager(this.getContext(), 1));
recyclerView.setAdapter(customAdapter);
//Adapter
public class GridViewAdapter extends RecyclerView.Adapter<GridViewAdapter.ViewHolder>{
private List<RecyclerItem> dataItems;
private int hSpan = 1;
private String packageName;
private final OnItemClickListener listener;
private int inflator;
private int vSpan;
public interface OnItemClickListener {
void onItemClick(RecyclerItem item);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final ConstraintLayout constraintLayout;
private final TextView textView;
private final ImageView imageView;
private Object obj;
public ViewHolder(View view) {
super(view);
constraintLayout = (ConstraintLayout) view.findViewById(R.id.rec_content_layout);
textView = constraintLayout.findViewById(R.id.recTextView);
imageView = constraintLayout.findViewById(R.id.recImage);
}
public void bind(final RecyclerItem item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
public TextView getTextView() {
return textView;
}
public ImageView getImageView() {
return imageView;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
public GridViewAdapter(List<RecyclerItem> items, int spanCount, String packageName, OnItemClickListener listener,
int inflator, int vSpan) {
dataItems = items;
this.hSpan = spanCount;
this.packageName = packageName;
this.listener = listener;
this.inflator = inflator;
this.vSpan = vSpan;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int gridType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(inflator, viewGroup, false);
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = (viewGroup.getResources().getDisplayMetrics().widthPixels / hSpan) - 24;
if(Constants.V_SPAN_GRID == vSpan) {
layoutParams.height = layoutParams.width;
} else {
layoutParams.height = (viewGroup.getResources().getDisplayMetrics().widthPixels / vSpan);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
viewHolder.getTextView().setText(dataItems.get(position).getText());
int imgId = viewHolder.getImageView().getResources().getIdentifier(
dataItems.get(position).getImageName(), "drawable", packageName);
viewHolder.getImageView().setImageResource(imgId);
viewHolder.setObj(dataItems.get(position));
viewHolder.bind(dataItems.get(position), listener);
}
#Override
public int getItemCount() {
return dataItems.size();
}
//item layout
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rec_content_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginTop="8dp"
android:layout_marginLeft="4dp"
android:padding="8dp"
android:background="#drawable/border_top_bottom" >
<androidx.constraintlayout.widget.Guideline
android:id="#+id/viewstock_gline_1_v"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.6"/>
<ImageView
android:id="#+id/recImage"
android:background="#color/colorPrimaryDark"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp" />
<TextView
android:id="#+id/recTextView"
app:layout_constraintLeft_toRightOf="#+id/recImage"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp" />
<ImageView
android:id="#+id/editstock_image"
android:src="#drawable/ic_edit_stock"
android:background="#color/colorPrimaryDark"
app:layout_constraintRight_toLeftOf="#+id/deletestock_image"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp" />
<ImageView
android:id="#+id/deletestock_image"
android:src="#drawable/ic_delete_stock"
android:background="#color/colorPrimaryDark"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp" />
</androidx.constraintlayout.widget.ConstraintLayout>```

Try this!
public void bind(final RecyclerItem item, final OnItemClickListener listener, TextView itemTextView) {
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
Pass every item text view instance from the view holder or fro onBindViewHolder itself implement onclick listener

Related

Why these random marks are appearing in every recyclerview and viewpager items?

I have 2 recycler views and a view pager in a fragment.
Everything else works fine but both recycler view items are showing a random mark on the upper left corner of every items. And same thing is happening for the view pager items.
This fragment is in a fragment activity and view pager is using pager adapter. And I am using Picasso library to load images on the items and also using network policy to cache the images in disk.
recycler view items appearing like this
view pager items appearing like this
Recycler View adapter
public class CourseListAdapter extends RecyclerView.Adapter<CourseListAdapter.CourseListViewHolder> {
public static final int HOME_PAGE = 1;
public static final int DISPLAY_COURSE = 2;
private Picasso mPicasso;
private List<DisplayCourse> courseList;
private static final String TAG = "CourseListAdapter";
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position, View view);
}
private String mSender;
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public CourseListAdapter(List<DisplayCourse> courseList, String sender) {
this.courseList = courseList;
this.mSender = sender;
mPicasso = Picasso.get();
}
#NonNull
#Override
public CourseListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 1:
View view1 = inflater.inflate(R.layout.recom_course_home_layout, parent, false);
return new CourseListViewHolder(view1, mListener);
case 2:
View view2 = inflater.inflate(R.layout.display_course_layout, parent, false);
return new CourseListViewHolder(view2, mListener);
default:
View view3 = inflater.inflate(R.layout.section_video_item_layout, parent, false);
return new CourseListViewHolder(view3, mListener);
}
}
#Override
public void onBindViewHolder(#NonNull CourseListViewHolder holder, int position) {
holder.title.setText(courseList.get(position).getCourseTitle());
mPicasso.load(courseList.get(position).getThumbnailURL())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(holder.thumbnail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
mPicasso.load(courseList.get(position).getThumbnailURL())
.error(R.drawable.ofklogo)
.into(holder.thumbnail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
}
});
}
#Override
public int getItemCount() {
return courseList.size();
}
public static class CourseListViewHolder extends RecyclerView.ViewHolder {
ImageView thumbnail;
TextView title;
public CourseListViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
title = itemView.findViewById(R.id.courseTitle);
thumbnail = itemView.findViewById(R.id.courseThumbNailImageView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null) {
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position, view);
}
}
}
});
}
}
#Override
public int getItemViewType(int position) {
if (mSender.equals("home_page")) {
return HOME_PAGE;
} else if (mSender.equals("displayCourse")) {
return DISPLAY_COURSE;
}
return -1;
}
}
View pager adapter
public class VideoSliderAdapter extends PagerAdapter {
private boolean doNotifyDataSetChangedOnce = false;
private static final String TAG = "VideoSliderAdapter";
private YouTubePlayerView youTubePlayerView;
private View gradientView;
private ImageView thumbNail;
private LinearLayout layout;
private Picasso picasso;
private List<Video> videoList;
private Context mContext;
private Lifecycle mLifeCycle;
public VideoSliderAdapter(List<Video> videoList, Context context, Lifecycle lifecycle) {
this.videoList = videoList;
this.mContext = context;
this.mLifeCycle = lifecycle;
doNotifyDataSetChangedOnce = true;
picasso = Picasso.get();
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return videoList.size();
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return (view == (CardView) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.video_paly_layout, container, false);
TextView title = view.findViewById(R.id.videoTitle);
title.setText(videoList.get(position).getVideoTitle());
gradientView = view.findViewById(R.id.gradientView);
thumbNail = view.findViewById(R.id.videoThumbNail);
picasso.load(videoList.get(position).getVideoThumbNail())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(thumbNail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
picasso.load(videoList.get(position).getVideoThumbNail())
.error(R.drawable.ofklogo)
.into(thumbNail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
}
});
layout = view.findViewById(R.id.videoPlayLayout);
youTubePlayerView = view.findViewById(R.id.youtube_player_view);
mLifeCycle.addObserver(youTubePlayerView);
new AddListener(youTubePlayerView, position).execute();
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((CardView) object);
}
Recycler view holder layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="150dp"
android:layout_height="200dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/courseThumbNailImageView"
android:layout_width="match_parent"
android:layout_height="130dp"
android:layout_alignParentTop="true"
android:scaleType="fitXY"
android:src="#drawable/art_thumb" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/courseThumbNailImageView">
<TextView
android:id="#+id/courseTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="2"
android:text="Course title"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
view pager layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.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="200dp"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:autoPlay="false" />
<ImageView
android:id="#+id/videoThumbNail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<View
android:id="#+id/gradientView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_drawable" />
<LinearLayout
android:id="#+id/videoPlayLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:padding="8dp"
android:src="#drawable/play_button" />
<TextView
android:id="#+id/videoTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="Course title"
android:textColor="#android:color/white"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When loading image using Picasso use: setIndicatorsEnabled(false)
picasso.load(videoList.get(position).getVideoThumbNail())
.networkPolicy(NetworkPolicy.OFFLINE)
.setIndicatorsEnabled(false)
.into(...);
The colors indicate this:
Green: Image is fetched from memory
Blue: Image is fetched from disk
Red: Image is fetched from network

How to make two Recyclerview in one Layout

i already success to make one Recyclerview and i want to add new Recyclerview Horizontal on top. i will explain in my code :
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayListUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
id:arrayList is my first Recyclerview have name xml feeds_listview
id:arrayListUser is my new Recyclerview, i want make this Recyclerview Horizontal
xml for new Recylerview is feeds_listviewUser
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profil"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="30dp"
android:layout_gravity="center"
android:src="#drawable/cthprofil" />
<TextView
android:id="#+id/fullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="5dp"
android:layout_marginBottom="20"
android:text="Megi Fernanda"
android:textSize="17sp"
android:textColor="#color/colordefault"
android:textStyle="bold" />
</LinearLayout>
and this is my class adapter
public class FeedsCustomAdapter extends RecyclerView.Adapter<FeedsCustomAdapter.ViewHolder> {
private Context context;
private List<FeedsAdapter> feeds_list;
private ArrayList<Feeds> mFeedsList = new ArrayList<Feeds>();
private OnItemClickListener mListener;
private OnItemClickListener mListener2;
public FeedsCustomAdapter(Context context, ArrayList<Feeds> mFeedsList) {
this.context = context;
this.mFeedsList = mFeedsList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.feeds_listview, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Feeds feed = getFeeds().get(position);
int textColor = context.getResources().getColor(R.color.btn_next);
int textColor2 = context.getResources().getColor(R.color.text_color_black);
holder.fullName.setText(feed.user.fullName);
holder.location.setText(feed.user.location);
holder.topic.setText(Html.fromHtml( "Menyelesaikan Tantangan " + " <font color = '" + String.valueOf(textColor2) + "'>" + feed.topic + "</font>" ) );
Picasso.with(context)
.load(feed.user.avatar)
.into(holder.profile);
PrettyTime prettyTime = new PrettyTime();
String times = prettyTime.format(DateUtil.timeMilisTodate(feed.timestamp * 1000));
holder.times.setText(times);
}
#Override
public int getItemCount() {
return mFeedsList.size();
}
public ArrayList<Feeds> getFeeds() {
return mFeedsList;
}
public void setComplete(int position) {
mFeedsList.get(position).isComplete = 1;
}
public boolean last() {
boolean result = false;
int total = mFeedsList.size();
for (int i = 0; i < mFeedsList.size(); i++) {
if (mFeedsList.get(i).isComplete == 1) {
total--;
}
}
if (total == 1) {
result = true;
}
return result;
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView fullName;
public TextView location;
public TextView topic;
public ImageView profile;
public TextView times;
public ViewHolder(View itemView) {
super(itemView);
fullName = (TextView) itemView.findViewById(R.id.fullName);
location = (TextView) itemView.findViewById(R.id.location);
topic = (TextView) itemView.findViewById(R.id.topic);
profile = (ImageView) itemView.findViewById(R.id.profil);
times = (TextView) itemView.findViewById(R.id.times);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mListener2 != null){
mListener2.onItemClick2(v ,getPosition());
}
}
});
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mListener != null){
mListener.onItemClick(v ,getPosition());
}
}
});
}
}
public void setClickListener(OnItemClickListener clickListener) {
this.mListener = clickListener;
}
public void setClickListenerProfile(OnItemClickListener clickListener2){
this.mListener2 = clickListener2;
}
public interface OnItemClickListener {
public abstract void onItemClick(View view, int position);
public abstract void onItemClick2(View view, int position);
}
so, in my code i success to display first recylerview with my first xml and i want add new recylerview horizontal with new xml feeds_listviewUser
You can use LinearLayout to wrap both recyclerView.
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayListUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:id="#+id/arrayList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#color/white">
</android.support.v7.widget.RecyclerView>
And assign horizontal layout manager to one recyclerview and vertical layout manager to other
LinearLayoutManager userManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
arrayListUser.setLayoutManager(userManager);
LinearLayoutManager listManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
arrayList.setLayoutManager(listManager);
Put your recyclerviews in Relative layout.
First add horizontal recyclerView to alignParentTop true and fix height according to visibility of feeds_listviewUser next add vertical recyclerView with layout_below horizontal recyclerview id.

ReclyclerView and CardView, onclick method perform the action on several CardViews at same time

I've got a RecyclerView which populates from an ArrayList. The output is a CardView layout.
In the Cardview, there are 2 buttons amongst other Views.
They only have to read the current value of a TextView, which by default is 1, and increase or decrease it.
The Arraylist contains 8 items.
When I run the app the UI works fine. Trouble is when I try to modify the value of the TextView.
The value is correctly increased and decreased on the CardView I'm working on, but ALSO the value is modified on another CardView. And in that second CardView, modifying its TextView value, also modifies the first one.
So, what am I doing wrong?
This is my Fragment:
public class Fragment_rosas extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_rosas,container,false);
RecyclerView recyclerview_rosas;
RecyclerView.Adapter adaptador_rv_rosas;
RecyclerView.LayoutManager lm_rosas;
List rosas = new ArrayList();
rosas.add(new Tropa(1,R.drawable.minibarbaro, getResources().getString(R.string.barbaro),7,1));
recyclerview_rosas = (RecyclerView) view.findViewById(R.id.recyclerView_tropasRosas);
recyclerview_rosas.setHasFixedSize(true);
lm_rosas = new LinearLayoutManager(getContext());
recyclerview_rosas.setLayoutManager(lm_rosas);
adaptador_rv_rosas = new AdaptadorTropa(rosas);
recyclerview_rosas.setAdapter(adaptador_rv_rosas);
return view;
}
}
And here the part of code on my Adapter:
#Override
public void onBindViewHolder(final TropaViewHolder viewHolder, int i) {
viewHolder.imagen.setImageResource(items.get(i).getImagen());
viewHolder.nombre.setText(items.get(i).getNombre());
viewHolder.maxnivel.setText(String.valueOf(items.get(i).getNivelMax()));
viewHolder.espacioencamp.setText((String.valueOf(items.get(i).getEspacioEnCamp())));
final String nombre = items.get(i).getNombre();
final int maxnivel = items.get(i).getNivelMax();
viewHolder.nivelmas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String niveltemp = viewHolder.nivel.getText().toString();
String nivelmaxtemp = viewHolder.maxnivel.getText().toString();
int nivel = Integer.parseInt(niveltemp);
int maxxnivel = Integer.parseInt(nivelmaxtemp);
int nuevonivel = nivel+1 ;
if (nuevonivel<=maxxnivel) {
viewHolder.txtv_nivel.setText(String.valueOf(nuevonivel));
}
}
});
My OnCreateViewHolder (nothing really happens here):
#Override
public TropaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.cardview, viewGroup, false);
return new TropaViewHolder(v);
}
Here is the solution, as mentioned in the comment above, it addresses two problems:
1. positiontoValueMap - saves current value for each position
2. onclicklistener is passed to the ViewHolder in onCreateViewHolder
Adapter Class
public class MyAdapter extends RecyclerView.Adapter {
private Context context;
private List<String> dataList;
private Map<Integer, Integer> positionToValueMap = new HashMap<>();
public MyAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_view_item, null, false);
return new MyViewHolder(view, new OnRecyclerItemClickListener());
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MyViewHolder) holder).onRecyclerItemClickListener.updatePosition(position);
((MyViewHolder) holder).position.setText("" + position);
((MyViewHolder) holder).title.setText(dataList.get(position));
int valueToDisplay = 1;
if(positionToValueMap.containsKey(position)) {
valueToDisplay = positionToValueMap.get(position);
} else {
positionToValueMap.put(position, valueToDisplay);
}
((MyViewHolder) holder).valueView.setText("value: " + valueToDisplay);
}
#Override
public int getItemCount() {
return dataList.size();
}
private class MyViewHolder extends RecyclerView.ViewHolder {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private TextView position;
private TextView title;
private TextView valueView;
public MyViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
itemView.setOnClickListener(onRecyclerItemClickListener);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.position = (TextView) itemView.findViewById(R.id.position);
this.title = (TextView) itemView.findViewById(R.id.title);
this.valueView = (TextView) itemView.findViewById(R.id.value_view);
}
}
private class OnRecyclerItemClickListener implements View.OnClickListener {
private int position = -1;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void onClick(View v) {
int oldValue = positionToValueMap.get(position); // get current value
oldValue++; // increment
positionToValueMap.put(position, oldValue); // save current value
notifyItemChanged(position); // update clicked view so that it picks up the new saved value from the positionToValueMap in onBindViewHolder
}
}
}
RecyclerView item layout
<TextView
android:id="#+id/position"
android:layout_width="30dp"
android:layout_height="50dp"
android:textColor="#android:color/white"
android:gravity="center"
android:background="#android:color/holo_green_light"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/title"
android:layout_width="50dp"
android:layout_height="50dp"
android:textColor="#android:color/white"
android:gravity="center"
android:background="#android:color/holo_green_dark"
android:layout_toRightOf="#id/position" />
<TextView
android:id="#+id/value_view"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#android:color/white"
android:gravity="center"
android:background="#android:color/holo_green_light"
android:layout_toRightOf="#id/title"
android:layout_alignParentRight="true"/>
</RelativeLayout>
And Activity to test it out
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(new MyAdapter(getApplicationContext(), getSampleData()));
}
private static List<String> getSampleData() {
List<String> dataList = new ArrayList<>();
dataList.add("zero");
dataList.add("one");
dataList.add("two");
dataList.add("three");
dataList.add("four");
dataList.add("five");
dataList.add("six");
dataList.add("seven");
dataList.add("eight");
dataList.add("nine");
dataList.add("ten");
dataList.add("eleven");
dataList.add("twelve");
dataList.add("thirteen");
dataList.add("fourteen");
dataList.add("fifteen");
dataList.add("sixteen");
dataList.add("seventeen");
dataList.add("eighteen");
dataList.add("nineteen");
dataList.add("twenty");
return dataList;
}
}
activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"/>
</RelativeLayout>

Contents of RecyclerView not visible

I am trying to create a ListView, each row of which is a horizontal scrolling list. Earlier, I was using HorizontalScrollView but I needed a layout which could recycle views. So I used RecyclerView, but now the contents of RecyclerView are not visible.
Here is my adapter for vertical listview:
public class FeedAdapter extends BaseAdapter {
private Context context;
private FeedItem feedItem;
private static LayoutInflater inflater = null;
private Picasso picasso;
Typeface opensans;
public FeedAdapter(Context context, FeedItem feedItem) {
this.context = context;
this.feedItem = feedItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
opensans = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
OkHttpClient okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(okHttpClient))
.build();
}
#Override
public int getCount() {
return feedItem.getFeedList().size();
}
#Override
public FeedList getItem(int position) {
return feedItem.getFeedList().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final FeedRowViewHolder rowViewHolder;
if (view == null) {
view = inflater.inflate(R.layout.feed_row, parent, false);
rowViewHolder = new FeedRowViewHolder(view);
view.setTag(rowViewHolder);
} else {
rowViewHolder = (FeedRowViewHolder) view.getTag();
}
final FeedList feedList = feedItem.getFeedList().get(position);
picasso.with(context)
.load(feedList.getThumbnailUrl())
.resize(120, 120)
.centerCrop()
.into(rowViewHolder.galleryThumb);
rowViewHolder.galleryThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String api_url = feedList.getUrl();
String delims = "/";
String[] tokens = api_url.split(delims);
String thumbId = tokens[5];
((HomeActivity) context).changeIntent(thumbId);
}
});
rowViewHolder.galleryName.setText(feedList.getGalleryName());
rowViewHolder.galleryName.setTypeface(opensans);
rowViewHolder.galleryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String api_url = feedList.getUrl();
String delims = "/";
String[] tokens = api_url.split(delims);
String thumbId = tokens[5];
((HomeActivity) context).changeIntent(thumbId);
}
});
rowViewHolder.timestamp.setText(feedList.getCreatedDate());
rowViewHolder.timestamp.setTypeface(opensans);
rowViewHolder.followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
picasso.with(context)
.load(R.drawable.cta_button_follow_secondary_state)
.into(rowViewHolder.followButton);
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
rowViewHolder.recyclerView.setLayoutManager(layoutManager);
FeedItemAdapter adapter = new FeedItemAdapter(context, feedList.getPhotos());
rowViewHolder.recyclerView.setAdapter(adapter);
return view;
}
static class FeedRowViewHolder {
#Bind(R.id.imageView75)
ImageView galleryThumb;
#Bind(R.id.textView65)
TextView galleryName;
#Bind(R.id.textView66)
TextView timestamp;
#Bind(R.id.imageView162)
ImageView followButton;
#Bind(R.id.recyclerView)
RecyclerView recyclerView;
public FeedRowViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Here is my adapter for Horizontal RecyclerView:
public class FeedItemAdapter extends RecyclerView.Adapter<FeedItemAdapter.ViewHolder> {
private List<Photo> list;
private Context context;
private Picasso picasso;
Typeface opensans;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Photo photo = getValueAt(position);
picasso.with(context)
.load(photo.getPhotoUrl())
.resize(1020, 768)
.centerCrop()
.into(holder.image);
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String photo_url = photo.getPhoto();
String delims = "/";
String[] tokens = photo_url.split(delims);
String photoId = tokens[5];
((HomeActivity) context).setBackImage(photoId);
}
});
picasso.with(context)
.load(photo.getProfilePic())
.resize(120, 120)
.centerCrop()
.transform(new CircleTransform())
.into(holder.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_url = photo.getOwner();
String delims = "/";
String[] tokens = user_url.split(delims);
String photoId = tokens[5];
((HomeActivity) context).showUserProfile(photoId);
}
});
holder.commentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showComments();
}
});
holder.fiveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showLikes();
}
});
holder.commentImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((HomeActivity) context).showComments();
}
});
holder.username.setText(photo.getUserName());
holder.username.setTypeface(opensans);
holder.userFives.setText(Integer.toString(photo.getUserFives()) + " Fives");
holder.userFives.setTypeface(opensans);
holder.caption.setText(photo.getCaption());
holder.caption.setTypeface(opensans);
final int[] fives = {photo.getPhotoFives()};
holder.numFives.setText(Integer.toString(photo.getPhotoFives()));
holder.numFives.setTypeface(opensans);
holder.numComments.setText(Integer.toString(photo.getNumComments()));
holder.numComments.setTypeface(opensans);
final boolean[] liked = {false};
holder.fiveButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
holder.fiveButton.setText("Hi Fiveeed!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#FAC80A"));
picasso.with(context)
.load(R.drawable.cta_ic_five_pressed_state)
.into(holder.fiveImage);
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
}
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
}
return false;
}
});
holder.fiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (liked[0] == false) {
holder.fiveButton.setText("Hi Fived!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#FAC80A"));
holder.numFives.setText(Integer.toString(fives[0] + 1));
fives[0] = fives[0] + 1;
picasso.with(context)
.load(R.drawable.cta_ic_five_pressed_state)
.into(holder.fiveImage);
liked[0] = true;
} else {
holder.fiveButton.setText("Five This!");
holder.fiveButton.setTypeface(opensans);
holder.fiveButton.setTextColor(Color.parseColor("#707070"));
holder.numFives.setText(Integer.toString(fives[0] - 1));
fives[0] = fives[0] - 1;
picasso.with(context)
.load(R.drawable.user_profile_activity_1_ic_five_count)
.into(holder.fiveImage);
liked[0] = false;
}
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public Photo getValueAt(int position) {
return list.get(position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.imageView86)
ImageView image;
#Bind(R.id.imageView76)
ImageView profilePic;
#Bind(R.id.textView67)
TextView username;
#Bind(R.id.textView68)
TextView userFives;
#Bind(R.id.textView1)
TextView caption;
#Bind(R.id.textView69)
TextView fiveButton;
#Bind(R.id.textView71)
TextView commentButton;
#Bind(R.id.imageView77)
ImageView fiveImage;
#Bind(R.id.textView72)
TextView numFives;
#Bind(R.id.imageView120)
ImageView commentImage;
#Bind(R.id.textView73)
TextView numComments;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public FeedItemAdapter(Context context, List<Photo> list) {
this.context = context;
this.list = list;
opensans = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
OkHttpClient okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(okHttpClient))
.build();
}
}
Here is my layout for row of listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroller_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#231f20"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout7"
android:background="#343031"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView75"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingRight="5dp"
android:src="#drawable/user_profile_activity_1_img_gallery_1_icon"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView75"
android:orientation="vertical"
android:paddingLeft="5dp">
<TextView
android:id="#+id/textView65"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0.8"
android:paddingBottom="2dp"
android:text="Wilderness"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/textView66"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:text="2 hrs."
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#707070"
android:textSize="12sp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView162"
android:src="#drawable/cta_button_follow_default_state"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The items for each row were getting displayed perfectly fine when I was using HorizontalScrollView but the contents of recyclerView are not getting displayed. I can't figure out what is the problem. Any help would be highly appreciated.
I think your problem is here RecyclerView's android:layout_height="wrap_content". Try to set this attribute to specific value.
Update
New release of Android Support Library 23.2:
The RecyclerView widget provides an advanced and flexible base for
creating lists and grids as well as supporting animations. This
release brings an exciting new feature to the LayoutManager API:
auto-measurement! This allows a RecyclerView to size itself based on
the size of its contents. This means that previously unavailable
scenarios, such as using WRAP_CONTENT for a dimension of the
RecyclerView, are now possible. You’ll find all built in
LayoutManagers now support auto-measurement.
As mr.icetea said you need to set the layout-height to a specific amount. You could get the shown items height and pass that on to the layout-height param.
https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html documentation for adding layoutparams on the fly.
check out this method to calculate recyclerview height dynamically
// calculating height of Recycler view
private int calculateHeight(int size,int viewHeight) {
final float scale = mContext.getResources().getDisplayMetrics().density;
int singleViewHeight = (int) (viewHeight * scale + 0.5f);
int totalHeight = singleViewHeight * size;
return totalHeight;
}
and set height to recyclerview as-
//get recyclerview height
int height = calculateHeight(firstParam, secondparam);
ViewGroup.LayoutParams params = recyclerView.getLayoutParams();
params.height = height;
firstparam is sizofYourDataList_or_Array and secondparam is height of your row for recyclerview(so you have to give height for your row layout and that wiil be your second parameter's value)

unable to understand onClick event for multiple CardViews inside RecycleView

I looked up for the possible solutions but I could not figure out how to apply them in my case.
I am using a RecyclerView to display several CardViews inside it. Initially all cards have white background and I want to change the background color when a card is touched. Each CardView displays a name and an id as described in 'MyCards' class :
public class MyCards {
private String sName;
private int sId;
private boolean sPresent;
public String getName() {
return this.sName;
}
public MyCards(String sName, int sId, boolean sPresent) {
this.sName = sName;
this.sId = sId;
this.sPresent = sPresent;
}
public void setName(String t) {
this.sName = t;
}
public int getId() {
return sId;
}
public void setId(int id) {
this.sId = id;
}
public boolean isPresent() {
return sPresent;
}
public void setPresent(boolean present) {
this.sPresent = present;
}
}
I am making an ArrayList of these MyCards object in the 'Roster' class :
public class Roster extends ActionBarActivity{
private static final int READ_REQUEST_CODE = 42;
private static final String TAG = null;
private RecyclerView rObject;
private MyAdapter adapter;
String abc = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roster_recycle);
rObject = (RecyclerView)findViewById(R.id.recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
rObject.setLayoutManager(llm);
MyCards c1 = new MyCards("Abhinav", 123, true);
MyCards c2 = new MyCards("Abhishek", 13, false);
performFileSearch();
c1.setName("Abhinav");
c2.setName("Baba");
List<MyCards> cardList = new ArrayList<MyCards>();
cardList.add(c1);
cardList.add(c2);
adapter = new MyAdapter(Roster.this,cardList);
rObject.setAdapter(adapter);
}
The CardView is defined in the item_layout.xml file :
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="4dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/sName"
android:layout_width="match_parent"
android:layout_height="20dp"
android:gravity="center_vertical"
android:text="contact det"
android:textSize="14dp" />
<TextView
android:id="#+id/sId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/sName"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="Name"
android:textSize="10dp" />
<TextView
android:id="#+id/sPresent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/sId"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="Present"
android:textSize="10dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
My question is : If I click on a card displaying data for 'c1' object then how can I identify that it was from 'c1' and not 'c2'. How do I use click handler in such cases where we display multiple cards?
I'm sorry if my question is too basic but I'm really stuck at it.
Thank you so much for your responses, they really helped. Finally I found a video on YouTube which explained the concept in a nice manner. I am posting the link so that others can also benefit if they get stuck. Here is the video -
see this :- https://www.youtube.com/watch?v=zE1E1HOK_E4
Take a look at this answer for using an onItemClickListener with a RecyclerView.
public class MyAdapter extends RecyclerView.Adapter {
Context mContext;
ArrayList<MyCard> mData;
public MyAdapter(Context context , ArrayList<MyCard> data ) {
mContext = context;
mData = data;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView sName, sId , sPresent;
public ViewHolder(View itemView) {
super(itemView);
sName = (TextView) itemView.findViewById(R.id.sName);
sId = (TextView) itemView.findViewById(R.id.sId);
sPresent = (TextView) itemView.findViewById(R.id.sPresent);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your logic
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout , parent , false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemCount() {
return mData.size();
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final MyCard card = mData.get(position);
holder.sName.setText(card.getName().toString());
holder.sId.setText(card.getId().toString());
holder.sPresent.setText(card.getPresent().toString());
}
}

Categories

Resources