I have a program with 4 different tabs.
One of these tabs is an ActivityGroup which has a ListView in it. When I click on one of the list items, it switches to WebActivity:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(TabActivity2.this, WebActivity.class);
Bundle b = new Bundle();
b.putString("URL", URLs[(int)id]);
b.putString("prevActivity", "TabActivity2");
intent.putExtras(b);
replaceContentView("web", intent);
}
});
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}
So now we’re in the WebActivity class. Here’s the code:
public class WebActivity extends ActivityGroup {
WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
Bundle b = getIntent().getExtras();
String URL = b.getString("URL");
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl(URL);
mWebView.setWebViewClient(new FirstTabWebViewClient());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
Bundle b = getIntent().getExtras();
String retActivity = b.getString("prevActivity");
if (retActivity == "TabActivity2") {
Intent intent = new Intent(WebActivity.this, TabActivity2.class);
replaceContentView("list_webpages", intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}
Here’s the strange thing: If I click on the back button right after I enter the WebActivity class, it closes the application.
But if I first click on any link inside the WebView and then press back twice, then it returns me to the original activity with the ListView.
From using break points in Eclipse I discovered that the program does not even visit onKeyDown if I press the Back button right after I enter the WebActivity view. However, if I click on any link within the WebView and then press the back button, then it goes through my onKeyDown method.
What is going on here??
Your WebView doesn’t have the focus, which causes the back button to be triggered on top of that (the application stack). If you click on a link it get’s back focus. The WebView has some strange issues concerning focus, have look at this post: Android WebView focus problem
There you will also find some suggested workarounds to get the focus, you need to call requestFocus() on the WebView at the right place.