Question Detail

I am created a List of Search Keywords on Google in RecyclerView List I want to open details page on single click of the RecyclerView itemclick listener and want to delete Clicked Item onLongClick

 

How can we implement Click listener and LongclickListner with my RecyclerView item click listener and Long item click listener in android


Thread Reply

Anonymous

- 10 months ago

You have made some Java files in Android Project like :

 

import android.view.View;

/**
 * Created by Hemant Sharma on 2/2/2018.
 */
public interface ClickListener{
    public void onClick(View view,int position);
    public void onLongClick(View view, int position);
}

 

 

RecyclerTouchListener

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Hemant Sharma on 2/2/2018.
 */

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{

    private ClickListener clicklistener;
    private GestureDetector gestureDetector;

    public RecyclerTouchListener(Context context, final RecyclerView recycleView, 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=recycleView.findChildViewUnder(e.getX(),e.getY());
                if(child!=null && clicklistener!=null){
                    clicklistener.onLongClick(child,recycleView.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.getChildAdapterPosition(child));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

 

 

ADD THIS IS IN YOUR MAIN ACTIVITY

googleSearchList_recycler_view.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), googleSearchList_recycler_view, new ClickListener() {
    @Override
    public void onClick(View view, final int position) {
        Intent intent = new Intent(getActivity(), DetailsActivity.class);
        intent.putExtra("ID", YOUR_ID_OF_ARRAY[position]);
        startActivity(intent);
    }
    @Override
    public void onLongClick(View view, int position) {
        Toast.makeText(getActivity(), "Long press on position :" +position,Toast.LENGTH_LONG).show();
    }
}));