Horizontal RecycleView Item click scroll to first item - android

Hello guys i am having an issue with Horizontal Recycle View in which if am scroll to right then click on any item then it automatically scroll to first item in left , basically i have to stay on current clicked position not to scroll to start left , i use multiple thing from stack but none of them worked like scrolltopostion, creating custom layout manager class !!! Please Help
Below is my code:
private void setAdapter() {
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(mLayoutManager);
mainAdapterClass = new MainAdapterClassw(context, AuctionManager.list);
recyclerView.setAdapter(mainAdapterClass);
}
Below is adapter Class:
public class MainAdapterClassw extends RecyclerView.Adapter<MainAdapterClassw.ViewHolder> {
ArrayList<AuctionBean> list;
Context context;
public MainAdapterClassw(Context context, ArrayList<AuctionBean> list) {
super();
this.context = context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.customelayout, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
auctionBean = list.get(i);
viewHolder.top_sr_no.setText(auctionBean.getAuction_id());
viewHolder.view2.setVisibility(View.GONE);
viewHolder.itemView.setSelected(selectedPos == i);
viewHolder.bottom_sr_no.setText(auctionBean.getReserve_price());
text_qantity.setText(qantity1);
Picasso.with(context)
.load("http://traala.com/Bidding/images/date.png")
.placeholder(R.mipmap.ic_launcher)
.into(productimage);
}
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
AuctionBean auctionBean1 = list.get(position);
Log.d("LogPosition",position+"");
if (countDownTimer != null) {
countDownTimer.cancel();
}
CSPreferences.putString(context, "auction_id", auctionBean1.getAuction_id());
ModelManager.getInstance().getAuctionManager().AuctionManager(context, Operations.getallAcuntion(context,
ActionString.getall_auctions, "101", auctionBean1.getAuction_id()));
}
});
switch (auctionBean.getAuction_status()) {
case "status_active.png":
viewHolder.imgThumbnail.setImageResource(R.drawable.status_active);
break;
case "status_pending.png":
viewHolder.imgThumbnail.setImageResource(status_pending);
break;
case "status_over.png":
viewHolder.imgThumbnail.setImageResource(R.drawable.ic_icon_auction_red);
break;
}
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView imgThumbnail;
public TextView top_sr_no;
public TextView bottom_sr_no;
View view2;
private ItemClickListener clickListener;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.imageview);
top_sr_no = (TextView) itemView.findViewById(R.id.textsrno);
bottom_sr_no = (TextView) itemView.findViewById(R.id.textbottom_srno);
view2 = (View) itemView.findViewById(R.id.view1);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public void onClick(View view) {
clickListener.onClick(view, getAdapterPosition(), false);
adapterpostion =getAdapterPosition();
auctionstatus =auctionList.get(getAdapterPosition());
}
#Override
public boolean onLongClick(View view) {
clickListener.onClick(view, getPosition(), true);
return true;
}
}
}
}

Please add this property in your parent layout in xml file
android:descendantFocusability="blocksDescendants"
Set adapter in RecyclerView as below:
private void setAdapter() {
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
mainAdapterClass = new MainAdapterClassw(context, AuctionManager.list);
recyclerView.setAdapter(mainAdapterClass);
}

In my case it was occurred because of gravity property inside EditText, It was like: android:gravity="center", So removing this property resolved the issue.

Related

How to hide recyclerview's all item in activity

I want to hide checkbox of all lists if I clicked one list within activity using recyclerview.
But when I implement it, only the check box in the recyclerview list of the clicked position disappears. How can I hide the checkbox of the entire list?
Of course it is possible on the reyclerview adapter, but I want this function to be implemented in activity.
In activity, the adapter was declared:
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewAdapter = new RecyclerViewAdapter(this, patientList, selected_patientList);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recyclerViewAdapter);
And I wrote the code that hides the check box when click the recyclerview list in activity :
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox) ;
checkBox.setVisibility(View.GONE);
}
And my recyclerview adapter code is
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Activity activity;
public ArrayList<PatientItem> patientList = new ArrayList<>();
public ArrayList<PatientItem> selected_patientList = new ArrayList<>();
Context mContext;
boolean checkboxIsVisible = true ;
public RecyclerViewAdapter(Context context, ArrayList<PatientItem> patientList, ArrayList<PatientItem> selected_patientList) {
this.mContext = context;
this.patientList = patientList;
this.selected_patientList = selected_patientList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView patientType;
TextView clinicID;
TextView patientName;
TextView dateFirst;
TextView dateFinal;
CheckBox checkBox ;
ConstraintLayout cl_listitem;
public MyViewHolder(View itemView) {
super(itemView);
patientType = (TextView) itemView.findViewById(R.id.typeViewItem);
clinicID = (TextView) itemView.findViewById(R.id.clinicIDItem);
patientName = (TextView) itemView.findViewById(R.id.patientNameItem);
dateFirst = (TextView) itemView.findViewById(R.id.dateFirstItem);
dateFinal = (TextView) itemView.findViewById(R.id.dateFinalItem);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox) ;
cl_listitem = (ConstraintLayout) itemView.findViewById(R.id.cl_listitem);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.patient_list_item, parent, false);
final RecyclerViewAdapter.MyViewHolder vHolder = new RecyclerViewAdapter.MyViewHolder(itemView) ;
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
PatientItem data = patientList.get(position);
holder.patientType.setText(data.getPatientType());
holder.clinicID.setText(data.getClinicID());
holder.patientName.setText(data.getPatientName());
holder.dateFirst.setText(data.getDateFirst());
holder.dateFinal.setText(data.getDateFinal());
holder.checkBox.setChecked(data.isDeleteBox());
holder.checkBox.setVisibility(checkboxIsVisible?View.VISIBLE:View.GONE);
if(data.getPatientType() == "P"){
holder.patientType.setText("");
holder.patientType.setBackground(ContextCompat.getDrawable(mContext, R.drawable.parkinson));
}
else if(data.getPatientType() == "ET"){
holder.patientType.setText("");
holder.patientType.setBackground(ContextCompat.getDrawable(mContext, R.drawable.essential_tremor));
}
else{
holder.patientType.setText("ㅡ");
}
}
#Override
public int getItemCount() {
return patientList.size();
}
public void clear() {
int size = patientList.size() ;
patientList.clear() ;
notifyItemRangeRemoved(0, size);
}
//어댑터 정비
public void refreshAdapter() {
this.selected_patientList = selected_patientList;
this.patientList = patientList;
this.notifyDataSetChanged();
}
}
I solved this problem like this.
I declared onBindViewHolder at RecyclerViewAdapter:
holder.checkBox.setVisibility(checkboxIsVisible?View.VISIBLE:View.GONE);
And, I declared visible() method in RecyclerViewAdapter :
public void visible(){
checkboxIsVisible = false ;
this.notifyDataSetChanged();
}
Than, I use visible method in activity :
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
recyclerViewAdapter.visible();
}
When I run this, when I click on one list, all the check boxes on the list disappear.

RecyclerView and Admob Items: Problems with onClickListener

I've added a NativeExpressAdView inside my RecyclerView ItemList but now the onClickListener is interfering with the NativeExpressAdView. My "normal" Items consist of text and one larger Image. When the larger Image gets clicked on, a DialogFragment gets opened and shows detailed information of the Item. However, the NativeExpressAdView shouldn't run into this onClickListener. The App keeps crashing because it tries to open the not existing detailed View of the NativeExpressAdView ...
MainActivity
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
recyclerView.addOnItemTouchListener(new ItemAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ItemAdapter.ClickListener() {
#Override
public void onClick(View view, final int position) {
final Bundle bundle = new Bundle();
bundle.putSerializable("events", events);
bundle.putInt("position", position);
final Event event = events.get(position);
detailView = (ImageView) view.findViewById(R.id.item_thumbnail);
detailView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.setCancelable(true);
newFragment.show(ft, "slideshow");
}
});
....
some other button onClickListener()...
....
}
#Override
public void onLongClick(View view, int position) {
}
}));
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<Event> events;
private Context mContext;
public ItemAdapter(Context context, List<Event> events){
mContext = context;
this.events = events;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{ // implements View.OnClickListener {
public ImageView thumbnail;
public TextView event_name;
public TextView event_date;
public TextView event_descr;
public TextView event_attending;
public TextView event_maybe;
public MyViewHolder(android.view.View view){
super(view);
thumbnail = (ImageView) view.findViewById(R.id.item_thumbnail);
event_name = (TextView) view.findViewById(R.id.tV_event_name);
event_date = (TextView) view.findViewById(R.id.tV_event_date);
event_descr = (TextView) view.findViewById(R.id.tV_event_descr);
event_attending = (TextView) view.findViewById(R.id.tV_attending_count);
event_maybe = (TextView) view.findViewById(R.id.tV_maybe_count);
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public NativeExpressAdView nativeExpressAdView;
public ViewHolderAdMob(View view) {
super(view);
nativeExpressAdView = (NativeExpressAdView) view.findViewById(R.id.ad_nativeAdOne);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("228****************************")
.build();
nativeExpressAdView.loadAd(adRequest);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_items, parent, false);
switch (viewType){
case 1:{
View itemView = inflater.inflate(R.layout.rv_items, parent, false);
viewHolder = new MyViewHolder(itemView);
break;
}
case 2:{
View itemView = inflater.inflate(R.layout.native_ad_one, parent, false);
viewHolder = new ViewHolderAdMob(itemView);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){
Event event = events.get(position);
switch (holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.event_name.setText(event.getEventName());
viewHolder.event_date.setText(event.getEventDate());
viewHolder.event_descr.setText(event.getEventDescription());
viewHolder.event_attending.setText(event.getEventAttending());
viewHolder.event_maybe.setText(event.getEventMaybeComming());
Glide.with(mContext).load(event.getEventImage())
.thumbnail(0.9f)
.crossFade()
//.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.into(viewHolder.thumbnail);
break;
}
case 2:{
break;
}
}
}
#Override
public int getItemCount(){
return events.size();
}
#Override
public int getItemViewType(int position) {
return events.get(position).getViewType();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ItemAdapter.ClickListener clickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ItemAdapter.ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e){
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e){
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e){
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept){
}
}
}
I kind of see where the problem stems from, since the the RecyclerView is listening for input and naturally reacts to it but I kind of thought that by defining inside my MainActivity that detailView = (ImageView) view.findViewById(R.id.item_thumbnail); it will only react to "normal" items since R.id.item_thumbnail is an element of my "normal" items xml whereas the NativeExpressAdView doesn't have such an element. How can I fix this problem and get the proper functionality ??
Set the click listener in onBindViewHolder, in your adapter, depending on the view type.
public static class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final MyListClickListener clickListener;
public ItemAdapter(MyListClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == ADVERT_VIEW_TYPE) {
// do whatever you do for adverts
} else {
// do what you do for items and set the click listener
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onShowDetailViewClicked(); // pass the parameters you need to identify this particular item
}
});
}
}
public interface MyListClickListener {
void onShowDetailViewClicked();
}
}
You are setting the onItemTouchListener{...} to the entire RecyclerView. It assumes that no matter where you touch, there is the detail view. But you have different types of rows in your RecyclerView. The best option would be to add touch listeners to each individual item in your ViewHolder classes.

Send data from CardView in RecyclerView to new fragment?

So I have a CardView in a RecyclerView which has some data inside it. I would like to click on a specific card and launch a new fragment that displays specific data from the data in the CardView (more details about the data in the CardView). Here is the relevant code.
I don't have the most experience in programming and Android in general, any help would be appreciated!
DetailsFragment: `
public class DetailsFragment extends Fragment {
private CardView cardView;
private RecyclerView rv;
private List<Detail> detailList = new ArrayList<>();
public DetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
Context context = getActivity();
cardView = (CardView) rootView.findViewById(R.id.cv);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(context);
rv.setLayoutManager(llm);
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData() {
detailList = new ArrayList<>();
// not sure here
detailList.add(new Detail(" "));
}
private void initializeAdapter(){
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
}
}
RVNewsAdapater:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK ="link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = null;
for(int postion = 0; postion<42; postion++) {
intent = new Intent(context, Details.class);
}
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
RVDetailAdapter:
public class RVDetailAdapter extends RecyclerView.Adapter<RVDetailAdapter.DetailViewHolder> {
public static class DetailViewHolder extends RecyclerView.ViewHolder {
TextView link;
public DetailViewHolder(View itemView) {
super(itemView);
link = (TextView) itemView.findViewById(R.id.link);
}
}
List<Detail> detail;
RVDetailAdapter(List<Detail> detail) {
this.detail = detail;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVDetailAdapter.DetailViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
DetailViewHolder dvh = new DetailViewHolder(v);
return dvh;
}
#Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int i) {
detailViewHolder.link.setText(detail.get(i).link);
}
#Override
public int getItemCount() {
if (detail != null) {
return detail.size();
}
return 0;
}
}
Not sure if you're still looking for an answer, but I just saw the post and thought I'd give you one option.
When I'm using a RecyclerView (doesn't matter if it's using the CardView or not, it's the same for any list item), I create a a click listener for the view item in the Adapter. When the user clicks the item/cardview, I dispatch an item click event. It's your choice on how you respond - you can use a standard callback interface (and pass in your listener when you create the adapter) or use something like EventBus.
Here's an example of the code you would add to your adapter class:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClick(view);
}
});
return new ViewHolder(view);
}
private void itemClick(View view) {
//Handle item event here
//EventBus.getDefault().post(new ItemSelectedEvent(/*send apprpopriate data*/));
}

onClickListener in RecyclerView adapter?

I want to set up an onClickListener within my RecyclerView adapter so I can easily refer to the other views to retrieve their tags.
Is it possible to set up an onClickListener in a RecyclerView adapter? How would I do it? Would it affect performance?
Here is my RecyclerView adapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
private Context context;
private List<Post> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public LinearLayout mainLayout;
public TextView username;
public ImageView image;
public ViewHolder(LinearLayout view) {
super(view);
view.setOnCreateContextMenuListener(this);
mainLayout = (LinearLayout) view.findViewById(R.id.main_view);
username = (TextView) view.findViewById(R.id.username);
image = (ImageView) view.findViewById(R.id.image);
}
}
public PostRecyclerAdapter(Context context, List<Post> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
#Override
public PostRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post postItem = mDataset.get(position);
holder.username.setText(postItem.getUserame());
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
I would like to suggest a much simpler approach than the one given above.
in your adapter you would have written static view holder class right for that add the following code
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// your views declared here
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
// your view initialised here
cardView=itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.card_view:
// your logic
break;
}
}
}
by doing so you can handle individual click of your layout as well as the entire layout click
You can use GestureDetector for this. This is very simple to use :
Create A class RecyclerTouchListener :
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
and you can use this class as follow :
rvFilterOptions = (RecyclerView) rootView.findViewById(R.id.rvCommon);
rvFilterOptions.setHasFixedSize(true);
rvFilterOptions.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
rvFilterOptions.setLayoutManager(mLayoutManager);
rvFilterOptions.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rvFilterOptions, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
// Perform click operation and you can get post item from array using position
}
#Override
public void onLongClick(View view, int position) {
// Perform Long click operation
}
}));
Note : Concept is taken from LINK
This is simplest implementation but this will be inside recyclerviews adapter. If you want to get row item clicklistener in activity then use Interface.
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
private Context context;
private List<Post> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public LinearLayout mainLayout;
public TextView username;
public ImageView image;
public View mRowItem;
public ViewHolder(LinearLayout view) {
super(view);
view.setOnCreateContextMenuListener(this);
mRowItem = view;
mainLayout = (LinearLayout) view.findViewById(R.id.main_view);
username = (TextView) view.findViewById(R.id.username);
image = (ImageView) view.findViewById(R.id.image);
}
}
public PostRecyclerAdapter(Context context, List<Post> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
#Override
public PostRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post postItem = mDataset.get(position);
holder.username.setText(postItem.getUserame());
//Whole row item
holder.mRowItem.setTag(position);
holder.mRowItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
// handle your row item click.
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}

Removing item from RecyclerView

I am having trouble removing items from RecyclerView. When I click on delete, the item is removed from RecyclerView, but comes back when I open the app again. I'm hoping it is just a minor issue that someone here can point out or direct me to what area to troubleshoot. The removeItem(String item) in bold is what I think is the issue. You can't see it in this post, but it is "not used".
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Grocery> mListData;
private SQLGroceryHelper helper;
RecyclerViewAdapter adapter;
//Adapter's Constructor//
public RecyclerViewAdapter(List<Grocery> mDataList) {
this.mListData = mDataList;
}
//Provide a reference to the views for each contact item//
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView rowItem;
ImageButton purchasedButton;
ImageButton deleteButton;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.recycler_row);
rowItem = (TextView) itemView.findViewById(R.id.item_field1);
purchasedButton = (ImageButton) itemView.findViewById(R.id.item_purchased);
deleteButton = (ImageButton) itemView.findViewById(R.id.delete_item);
}
}
//Inflate the view based on the viewtype provided//
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Create a new view by inflating the row item xml//
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
//Set the view to the ViewHolder//
MyViewHolder holder = new MyViewHolder(row);
return holder;
}
//Display data at the specified position//
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.rowItem.setText(mListData.get(position).getTextItem());
holder.purchasedButton.setOnClickListener(new View.OnClickListener() {
//Ignore this click for now//
#Override
public void onClick(View v) {
removeItem(position);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeItem(position);
}
});
}
public void **removeItem**(String item) {
int position = mListData.indexOf(item);
if (position != -1) {
mListData.remove(item);
notifyItemRemoved(position);
}
}
public void removeItem(int position) {
mListData.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
if (mListData == null) {
return 0;
}
return mListData.size();
}
}
You are removing the data from local object, mListData I guess the original data object remains intact. Remove the data item from the original data object as well
Declare a interface
public interface AdapterCommunication{
void removeStringItem(int position);
}
then in your adapter
private AdapterCommunication mListener;
public void setOnClickListener(AdapterCommunication listener){
mListener = listener;
}
Then from your activity where you initialize the adapter
RecyclerViewAdapter adapter = new RecyclerViewAdapter(list);
adapter.setOnClickListener(new AdapterCommunication{
public void removeStringItem(int position){
list.remove(position);
adapter.notifyDataSetChanged();
}
});
In your adaper,
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.remove(position);
}
});

Categories

Resources