Question

This should be so simple, but I just can't find a working solution...

I have a DialogFragment that consists of a LinearLayout that contains a WebView. When the user navigates in the WebView I want him/her to be able to go back using the back button. When he/she reaches the start page (i.e. can't go back anymore), the back button should close the dialog.

I tried setCancelable(false) and fiddling around with an OnKeyListener on the DialogFragments root view (the one that's returned by inflate(), but it never seems to get called for the back button. I don't want to have to involve the Activity's onBackPressed(), it should be handled by the DialogFragment if at all possible...

Was it helpful?

Solution

So far, the solution I have found is to set the OnKeyListener of the WebView, like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.dialog_fragment_layout, container, false)

    webView = (WebView) v.findViewById(R.id.webView);
    webView.setOnKeyListener( keyListener );        

    return v;
}


OnKeyListener keyListener = new OnKeyListener() {            
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN ){
            if( webView.canGoBack() ){
                webView.goBack();
                return true;
            }
        }

        return false;
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top