简体   繁体   中英

How to implement onclick method on recyclerview?

It seems like a frequently asked question but it is not. So I want to execute a method on clicking recyclerview. I have nothing to do with recyclerview items. I want the app to recognize a screen tap to implement a method.

Here's the code:

xml

  <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="9"
     android:id="@+id/rl">
  <android.support.v7.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:layout_width="match_parent"
        android:layout_height="match_parent"
      android:clipToPadding="false"
      android:divider="@null"
      android:paddingTop="8dp"
      android:visibility="visible"
      />
  </RelativeLayout>

Java

 mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    mRecyclerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"sent",Toast.LENGTH_SHORT).show();
        }
    });

Now on tapping on recyclerview area, the toast doesn't show up.

I would imagine you would do the onItemClick but do the same thing to all of the items. So if you click on the area of the recyclerview, then you will definitely click on one of the items. So just call a method for any onItem

You can use something like this:

          mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                Toast.makeText(MainActivity.this,"sent",Toast.LENGTH_SHORT).show();
                return false;
            }
            @Override
            public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            }
            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM