简体   繁体   中英

disable touch events of RecyclerView (to prevent user touches)?

I have a RecyclerView in my app and it displays data. I want to disable user touch events of RecyclerView. I have tried the below code but it does not work.

recyclerView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }
});

Please help me.

As I had a similar use case a few days ago and stumbled upon this question just now:
you can add either

to your RecyclerView.

Example using RecyclerView.SimpleOnItemTouchListener :

recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        // true: consume touch event
        // false: dispatch touch event
        return true;
   }
});

I consumed the touch event while my SwipeRefreshLayout was doing background work by querying swipeLayout.isRefreshing() .

你可以使用 RecyclerView 函数public void setLayoutFrozen(boolean frozen)

Java:

recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        return true;
    }
});

Kotlin:

recyclerView.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
    override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
        return true
    }
})

Just use this, fixed my problems (;

If you return true touch events are disabled.

if Return false touch events are enable.

recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        return true;
   }
});

hope it helps..

您可以使用yourRecyclerView.suppressLayout(true)禁用用户交互

You can override the LinearLayoutManager canScrollHorizontally method

getRecyclerView().setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false) {
    @Override
    public boolean canScrollHorizontally() {
        return false;
    }
});

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