In this example we will explain how to handle/detect android Mobile Back Button in android programmatically.
/*This allows the system to properly navigate backward when the user presses the Back button. However, there are a few cases in which your app should manually specify the Back behavior
in order to provide*/
MainActivity.java
................................................................................................................................................................
package com.androidbeginner.testcode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
@SuppressLint("ResourceAsColor")
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle("Used Back Button");
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
Toast.makeText(getApplicationContext(), "On press Button :--Open PreviousActivity", Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
..................................................................................................................................................................
Back Button Navigation for fragment.
...................................................................................................................................................................
getSupportFragmentManager().beginTransaction().add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
..................................................................................................................................................................
Back Button Navigation for webview.
...................................................................................................................................................................
@Overridepublic void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
// Otherwise defer to system default behavior.
super.onBackPressed();
}
...................................................................................................................................................................
0 comments