3

I got a Recyclerview and a EditText in my layout.

When I click outside the EditText (i.e clicks on the Recyclerview) I want the Recyclerview to get focus and the EditText view to loose focus. I cant get this to work. If I put a empty FrameLayout above the Recyclerview everything works as expected but I cant scroll the Recyclerview. Why cant I set the Recyclerview to be clickable and focusable?

I set these attributes in my layout xml

android:clickable="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:focusedByDefault="true"

on my Recyclerview/FrameLayout.

Goran
  • 1,002
  • 3
  • 14
  • 29

1 Answers1

4

The reason your xml tags have no effect is how Android handles clicks. Every event goes through the view hierarchy of the layout. First, the very top level parent of the layout receives the event. If the top level layout does not handle the event, then it gets passed to the child under it and so on.

In your case the touch event is first sent to the FrameLayout and since it is handled, the event doesn't reach the RecyclerView and therefore you cannot scroll.

The correct way to handle touch is to set onTouchListener on both the RecyclerView and the child view. The onTouch on the RecyclerView is called first. You handle all your analyzing there (you can check x and y and also see if the touch falls inside a child view. you can also change the focus of each view dynamically).

If you don't want the child to also handle the touch return true;. Otherwise return false; and the touch event will trigger the onTouchListener of the child view.

SoroushA
  • 2,043
  • 1
  • 13
  • 29
  • 1
    I did this: recyclerview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { hideKeyboard(edittext); edittext.clearFocus(); return false; } }); – Goran Aug 24 '17 at 14:18
  • public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } – Goran Aug 24 '17 at 14:18