简体   繁体   中英

Calling onKeyDown with Viewpager and Fragments

How can i make the below code work with a viewpagers that is loading 3 fragments, all are webviews with different URL's. Im simply trying to make it so that when clicking back on whatever fragment, it calls web.goBack();

Here is the code i've used in normal activities, I guess i need recommendations on weather this code should be inside the indivisual fragments or inside the main viewpager. Any suggestions or examples, or code would be greatly appreciated.

public boolean onKeyDown(int KeyCode, KeyEvent event) {
    if ((KeyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(KeyCode, event);
} 

You can override this in main Activity and then in on onKeyDown(int KeyCode, KeyEvent event) get your ViewPagers current fragment. In the end you will able to do something like this :

public boolean onKeyDown(int KeyCode, KeyEvent event) {

//.. get your fragment

WebView web = fragment.getWeb();

if ((KeyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
    web.goBack();
    return true;
}
return super.onKeyDown(KeyCode, event);
} 

Best wishes.

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