2

In my main Activity I've set up a interface CentreKeyPress, and I have 4 Fragments in a ViewPager, and a few of them implement this, a few don't. The interface has an onBack method, for when the back button is pressed. Here's my current code

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        ViewPager pager = (ViewPager)findViewById(R.id.contact_view_pager);

        List<Fragment> frags = adapter.getFragments();

        try {
            ((CentreKeyPress) frags.get(pager.getCurrentItem())).onBack();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return super.onKeyUp(keyCode, event);
}

Is a try/catch loop the best way to check if a Fragment implements the interface, or is there some kind of method that I can use to check if it implements it? Or, alternatively, could my Fragment handle onKeyUp themselves?

Cœur
  • 37,241
  • 25
  • 195
  • 267
TMH
  • 6,096
  • 7
  • 51
  • 88

2 Answers2

3

Try to use keyword INSTANCEOF and check if fragments are instance of interface you can check this to: use of "Instance of" in java

Community
  • 1
  • 1
Unii
  • 1,587
  • 15
  • 33
1

Check whether fragment is a instanceof the given fragment

if(frags.get(pager.getCurrentItem()) instanceof CentreKeyPress){
    //fragment implements CentreKeyPress
}
TMH
  • 6,096
  • 7
  • 51
  • 88
Dehan Wjiesekara
  • 3,152
  • 3
  • 32
  • 46