Reputation: 5823
The Back button on android application doesn't work in android 2.3 and developing an application on eclipse and ubuntu system, My emulator also doesn't have an back button enabled, I can't figure out what is not working as even when create an apk and install my mobile it doesn't works ? please help me with this issue.
MainActivity.java:
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView myWebView;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
//myWebView.loadUrl("http://www.example.com");
//WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
//setting JS to work in html pages in app
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//myWebView.setInitialScale(50);
myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
myWebView.loadUrl("file:///android_asset/www/testhtml5.html");
//mWebView.loadUrl("http://beta.html5test.com/");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Upvotes: 0
Views: 98
Reputation: 3110
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Edit:
put this statement:
WebView myWebView;
inside of your Activity before the onCreate() method and you should be good to go.
Upvotes: 3
Reputation: 4222
In order to add custom functionality to the back button you need to override the OnBackPressed in your activity. Like this:
@Override
public void onBackPressed() {
//your custom actions
}
Upvotes: 1