4

In activity I have TabLayout, ViewPager and menu button (hamburger) in toolbar.

With arrows on my keyboard I am moving from tabs to view pager items without problems by default but I cannot achieve focus on toolbar menu button.

First of all I can't listen when KeyEvent.KEYCODE_DPAD_UP was pressed and I'm wondering why.

My code:

viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

tabLayout.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if ((keyEvent.getAction() == KeyEvent.ACTION_UP) && (i == KeyEvent.KEYCODE_DPAD_UP)) {
            toolbar.setFocusable(true);
            toolbar.setFocusableInTouchMode(true);
            tabLayout.setNextFocusUpId(R.id.toolbar);
            Log.d(TAG, "KEYCODE_DPAD_UP");
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            tabLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        }
        return false;
    }
});

What is wrong with my if-statement?

danyapd
  • 2,516
  • 1
  • 14
  • 23
  • Does your listener get called at all? – Sdghasemi Jul 07 '20 at 09:22
  • @Sdghasemi yes it is called. checked with debugger. – danyapd Jul 07 '20 at 09:32
  • Then why don't you add a watcher for `keyEvent.getAction() == KeyEvent.ACTION_UP` and `i == KeyEvent.KEYCODE_DPAD_UP` and determine which one is `false` or catch the actual `keyEvent` and action that's happening? – Sdghasemi Jul 07 '20 at 09:36
  • started checking and realize that setOnKeyListener called, but not overrided `public boolean onKey` inside - it didn't caled. – danyapd Jul 07 '20 at 09:59

1 Answers1

5

Have you tried overriding the activity onKeyDown method and calling your code there:

public class YourActivity extends AppCompatActivity {
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            // Your code here
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
Sdghasemi
  • 5,370
  • 1
  • 34
  • 42