0

Long click on row of recyclerview is not entered in onClick() I dont understand what is wrong with my code.Following are my MainActivity, adapter and row of my recyclerview which is made using cardview.

Following is my MainActivity.java

public class MainActivity extends AppCompatActivity implements RecyclerView.OnItemTouchListener,
        View.OnClickListener,
        ActionMode.Callback {

    ArrayList<ProductPojo> lastNameList;
    private RecyclerView recyclerView;
    private ProductAdapter adapter;
    private List<ProductPojo> albumList;
    GestureDetectorCompat gestureDetector;
    ActionMode actionMode;

    /////
    private ProgressDialog pDialog;
    ApiClass apigetOfferList;
    String response;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        albumList = new ArrayList<>();
        lastNameList = new ArrayList<ProductPojo>(12);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, final int position) {

                        Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
                        final EditText edittext = new EditText(MainActivity.this);
                        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                        alert.setMessage("Enter Your Last Name");
                        alert.setTitle("Fill me");

                        alert.setView(edittext);

                        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();

                                ProductPojo lNamePojo = new ProductPojo(edittext.getText().toString());
                                Log.d("lastNameList.size()", ""+lastNameList.size() +"  "+position);
                                if(!albumList.isEmpty() && lastNameList.size() != 0) {
                                    lastNameList.add(position, lNamePojo);
                                    Log.d("lastNameList.size()", ""+lastNameList.size());
                                }

                                adapter.notifyDataSetChanged();
                                adapter = new ProductAdapter(MainActivity.this, albumList, lastNameList);
                                recyclerView.setAdapter(adapter);
                            //    lName = edittext.getText().toString();


                            }
                        });

                        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                            }
                        });

                        alert.show();

                    }
                })
        );

       /* LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(llm);
        recyclerView.setAdapter( adapter );*/
        gestureDetector = new GestureDetectorCompat(this, new RecyclerViewDemoOnGestureListener());
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
        listViewLoaderTask.execute();


    }


    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

    private class ListViewLoaderTask extends AsyncTask<String, Void, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

            apigetOfferList = new ApiClass();
        }


        @Override
        protected String doInBackground(String... args) {
            response = apigetOfferList.xmlFetchFunction();
            return response;
        }


        @Override
        protected void onPostExecute(String res) {

            Log.d("res", "" + res);
            StringReader reader = new StringReader(res);

            ProductXmlParser productXmlParser = new ProductXmlParser();

            List<HashMap<String, String>> products = null;

            try {
                /** Getting the parsed data as a List construct */
                products = productXmlParser.parse(reader);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            Log.d("products", "" + products);

            for (int i = 0; i < products.size(); i++) {

                Log.d("productThumbnail", "" + products.get(i).get("productThumbnail"));
                ProductPojo album = new ProductPojo(products.get(i).get("productThumbnail"), products.get(i).get("productName"), products.get(i).get("categoryName"), products.get(i).get("productDescription"), products.get(i).get("numberOfRatings"), products.get(i).get("rating"), products.get(i).get("averageRatingImageURL"));

                albumList.add(album);
                lastNameList.add(album);
            }


            adapter = new ProductAdapter(MainActivity.this, albumList, lastNameList);
            adapter.notifyDataSetChanged();

            RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(MainActivity.this, 1);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapter);


            pDialog.dismiss();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {//in
        Log.d("RecyclerView","DemoActivity"+"onInterceptTouchEvent");
        gestureDetector.onTouchEvent(e);
        return false;
    }

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

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    private void myToggleSelection(int idx) {//in
        Log.d("RecyclerView","DemoActivity"+"myToggleSelection");
        adapter.toggleSelection(idx);
        String title = getString(R.string.selected_count, adapter.getSelectedItemCount());
        actionMode.setTitle(title);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.container_list_item) {//in
            // item click
            Log.d("RecyclerView","DemoActivity"+"item click");
            int idx = recyclerView.getChildLayoutPosition(view);
            if (actionMode != null) {
                myToggleSelection(idx);
                return;
            }
        }
    }

    private class RecyclerViewDemoOnGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {//in
            Log.d("RecyclerView","DemoActivity"+"onSingleTapConfirmed");
            View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
            onClick(view);
            return super.onSingleTapConfirmed(e);
        }

        public void onLongPress(MotionEvent e) {//in
            Log.d("RecyclerView","DemoActivity"+"onLongPress");
            View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (actionMode != null) {
                return;
            }
            // Start the CAB using the ActionMode.Callback defined above
            actionMode = startActionMode(MainActivity.this);
            int idx = recyclerView.getChildAdapterPosition(view);
            myToggleSelection(idx);
            super.onLongPress(e);
        }
    }

    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {//in
        // Inflate a menu resource providing context menu items
        Log.d("RecyclerView","DemoActivity"+"onCreateActionMode");
        MenuInflater inflater = actionMode.getMenuInflater();
        inflater.inflate(R.menu.menu_cab_recyclerviewdemoactivity, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {

    }
}

This is my Adapter class

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {

    private Context mContext;
    private List<ProductPojo> albumList;
    String lName;

    private List<DemoModel> items;
    private SparseBooleanArray selectedItems;


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView lastName, cat_name, product_name, product_design, numOfRatings, rate;
        public ImageView thumbnail1, thumbnail2;

        public MyViewHolder(View view) {
            super(view);

            lastName = (TextView) view.findViewById(R.id.lastName);
            product_name = (TextView) view.findViewById(R.id.product_name);
            product_design = (TextView) view.findViewById(R.id.product_design);
            cat_name = (TextView) view.findViewById(R.id.category_name);
            rate = (TextView) view.findViewById(R.id.rate);
            numOfRatings = (TextView) view.findViewById(R.id.noOfRatings);
            thumbnail1 = (ImageView) view.findViewById(R.id.thumbnail);
            thumbnail2 = (ImageView) view.findViewById(R.id.thumbnail2);


            view.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {

                    Toast.makeText(itemView.getContext(), " " + getItemId(), Toast.LENGTH_SHORT).show();

                }
            });

            view.setOnLongClickListener(new View.OnLongClickListener()
                                     {
                                         @Override
                                         public boolean onLongClick(View v)
                                         {
                                             Toast.makeText(v.getContext(), "Long Click Listerner Position is " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
                                             return false;
                                         }
                                     }
            );
        }
    }


    public ProductAdapter(Context mContext, List<ProductPojo> albumList, ArrayList<ProductPojo> lName) {
        this.mContext = mContext;
        this.albumList = albumList;
        selectedItems = new SparseBooleanArray();
    }

    public int getSelectedItemCount() {
        Log.d("RecyclerViewDemoAdapter","getSelectedItemCount");
        return selectedItems.size();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.album_card, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        ProductPojo album = albumList.get(position);


        holder.lastName.setText("Last Name : " + album.getlName());
        holder.product_name.setText("Product Name : " + album.getpName());
        holder.cat_name.setText("Category Name : " + album.getcName());
        holder.product_design.setText("Product Description : " + album.getpDesc());
        holder.rate.setText("Rating : " + album.getRating());
        holder.numOfRatings.setText("No.of ratings : " + album.getNoOfRatings());

        Drawable productDrawable = LoadImageFromProductLink(album.getpLink());
        holder.thumbnail1.setImageDrawable(productDrawable);
        // loading album cover using Glide library
        Glide.with(mContext).load(album.getpLink()).into(holder.thumbnail1);

        Drawable rateDrawable = LoadImageFromRateLink(album.getRateLink());
        holder.thumbnail2.setImageDrawable(rateDrawable);
        // loading album cover using Glide library
        Glide.with(mContext).load(album.getRateLink()).into(holder.thumbnail2);

    }

    private Drawable LoadImageFromProductLink(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    private Drawable LoadImageFromRateLink(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }


    @Override
    public int getItemCount() {
        return albumList.size();
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    public void toggleSelection(int pos) {
        if (selectedItems.get(pos, false)) {
            Log.d("RecyclerViewDemoAdapter","IftoggleSelection");
            selectedItems.delete(pos);
        } else {
            Log.d("RecyclerViewDemoAdapter","ElsetoggleSelection");
            selectedItems.put(pos, true);
        }
        notifyItemChanged(pos);
    }
}


**And this is my row**



 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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">

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_margin="@dimen/card_margin"
            android:elevation="3dp"
            card_view:cardCornerRadius="@dimen/card_album_radius">

            <LinearLayout
                android:id="@+id/container_list_item"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="?android:attr/selectableItemBackground"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/first"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/thumbnail"
                        android:layout_width="130dp"
                        android:layout_height="130dp"
                        android:layout_margin="5dp"
                        android:clickable="true"
                        android:padding="5dp"
                        android:scaleType="fitXY" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/lastName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:text="Product Name"
                            android:textColor="@color/colorPrimaryDark"
                            android:textSize="@dimen/backdrop_subtitle"
                            android:textStyle="bold"
                            android:visibility="gone" />


                        <TextView
                            android:id="@+id/product_name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_marginTop="20dp"
                            android:text="Product Name"
                            android:textColor="@color/album_title"
                            android:textSize="@dimen/album_title" />

                        <TextView
                            android:id="@+id/category_name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:text="Category Name"
                            android:textColor="@color/album_title"
                            android:textSize="@dimen/album_title" />
                    </LinearLayout>
                </LinearLayout>

                <TextView
                    android:id="@+id/product_design"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:gravity="center"
                    android:text="Product Design"
                    android:textColor="@color/album_title"
                    android:textSize="@dimen/album_title" />

                <LinearLayout
                    android:id="@+id/second"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/rate"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:text="Rate"
                            android:textColor="@color/album_title"
                            android:textSize="@dimen/album_title" />

                        <TextView
                            android:id="@+id/noOfRatings"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:text="No. of Ratings"
                            android:textColor="@color/album_title"
                            android:textSize="@dimen/album_title" />
                    </LinearLayout>

                    <ImageView
                        android:id="@+id/thumbnail2"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="10dp"
                        android:layout_marginRight="10dp" />
                </LinearLayout>


            </LinearLayout>
        </android.support.v7.widget.CardView>

    </LinearLayout>

Please help me guys..I'm waiting for ur answers..Thanks in Advance!

S.Mayuri
  • 1
  • 4

1 Answers1

0

Detail below

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        private Article mArticle;

        private TextView mNameTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
            mNameTextView = (TextView) itemView.findViewById(R.id.grid_item_article_name_textView);
        }

        public void bind(Article article) {
            mArticle = article;
            mNameTextView.setText(article.getName());
        }

        @Override
        public void onClick(View view) {
            // Context context = view.getContext();
            // mArticle.getName()
        }

        @Override
        public boolean onLongClick(View view) {
            // Handle long click
        }
    }

Handle on item long click on recycler view

Community
  • 1
  • 1
Ucdemir
  • 2,852
  • 2
  • 26
  • 44
  • 1
    Thanks for ur answer...Using this way I can handle long click but how can I achieve multi selection – S.Mayuri Jul 27 '16 at 04:49
  • You can use external library for this like this https://bignerdranch.github.io/recyclerview-multiselect/ – Ucdemir Jul 27 '16 at 07:17