I’m currently moving slowly but steady forward in the making of a Android application and Im currently learning how to create a new window and switch to it. This is going all well but I have one small problem. When I pressing the “go back” button closes the application even if I have choosed to go back when just that button is pressed.
@Override
public void onBackPressed() {
finish();
return;
}
Have I missed something or what?
Thanks in advance.
EDIT
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.menuItem1:
setContentView(R.layout.about);
return true;
case R.id.menuItem2:
System.exit(0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
EDIT 2: About.java
package weather.right;
import weather.right.now.R;
import android.os.Bundle;
public interface About {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
You need to use
Intentsto “switch windows”. A “window” is called anActivityin Android and you set the visual content of anActivityusing thesetContentView()method in theonCreate()call of theActivity.To launch another
Activityfrom your currentActivity, simply create anIntentwith a few parameters and callstartActivity()with thatIntent. Here’s an example:Don’t forget to include your second
Activityin the Android manifest file. AllActivitiesin your application must be included in that file.Other things to note is that you don’t really use
System.exit()in Android. Just callfinish(). It’s advised to let Android manage applications and its resources rather than doing it yourself, but if you want to make sure that your application really is shut down, feel free to useSystem.exit()anyway. There’s also no need for overridingonBackPressed()if you’re only callingfinish(). That’s standard behaviour in Android when you hit the back button.Also, you don’t call
setContentView()more than once perActivity. You start a newActivitywhen you need to change the visuals (or use one of the specialized Widgets to switch between layouts.This also explains why you’re experiencing your “problem”. You may have changed the layout of the
ActivityusingsetContentView(), but there’s still only oneActivityrunning – when you callfinish(), thatActivitygets closed. If you had started a secondActivitywith a different layout, like you’re supposed to do, Android would have closed that secondActivityand would have returned you to the first.