Search code examples
javaandroidandroid-layoutwebviewviewgroup

ViewGroup of WebViews History issue


I have a view group that allows users to swipe through 3 WebViews (layouts) in the same way as the Android home screen. A problem arises when the user presses the back button to go back in the currently displayed WebView's history. What happens is the history will go back for whichever of the 3 views was used last, and not the currently displayed WebView...

Here is my code which comes into effect when the user pressing the back button:

int backpress = 1;
Timer timer = new Timer();

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if ((keyCode == KeyEvent.KEYCODE_BACK) && WebView[0].canGoBack()) {
        WebView[0].goBack();
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_BACK) && WebView[1].canGoBack()) {
        WebView[1].goBack();
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_BACK) && WebView[2].canGoBack()) {
        WebView[2].goBack();
        return true;
    }

    else if(keyCode == KeyEvent.KEYCODE_BACK) {
            backpress = (backpress + 1);
            Toast.makeText(getApplicationContext(), " Press again to exit ", Toast.LENGTH_SHORT).show();
            timer.schedule(new RemindTask(), 2000); 


         if (backpress>2) {
            finish();
         }

    }

    return false;   
}

class RemindTask extends TimerTask {
    @Override
    public void run() {
        backpress = 1;

    }}

Is there a way to get the current focused WebView so that i can solve this issue?


Solution

  • Refer to this question to get the selected view from a ViewPager. Override onBackPressed or onKeydown in your activity so that you manually handle back presses and call goBack on the selected view.