Tom Hart Tom Hart -3 years ago 89
Android Question

How to check if Fragment implements an interface

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download