快速提问:我有一个活动组。在该活动组内,我有一项活动。如果我在此活动中按回来。调用活动的onBackPressed方法 - 不是活动组onBackPressed - 为什么?
编辑:得到了答案,但问题仍然存在。下面是我原始问题的代码和解释:我在TabHost中使用ActivityGroups,因此被“强制”覆盖onBackPressed。通过按下我的手机并按下我的tabhost上的标签,我可以毫无问题地浏览我的应用程序。但按Back后我无法与界面交互。 一旦我再次按下tabhost上的其中一个标签,我就可以正常地与所有内容进行交互。为什么会这样?我是否需要覆盖onResume?
相关代码
SettingsActivityGroup:
public class SettingsActivityGroup extends ActivityGroup
{
// Keep this in a static variable to make it accessible for all the nested activities, lets them manipulate the view
public static SettingsActivityGroup group;
// Need to keep track of the history if you want the back-button to work properly, don't use this if your activities requires a lot of memory.
private ArrayList<View> history;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Allocate history
this.history = new ArrayList<View>();
// Set group
group = this;
// Start root (first) activity
Intent myIntent = new Intent(this, SettingsActivity.class); // Change to the first activity of your ActivityGroup
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ReplaceView("SettingsActivity", myIntent);
}
/*
* Replace the activity with a new activity and add previous one to history
*/
public void ReplaceView(String pId, Intent pIntent)
{
Window window = getLocalActivityManager().startActivity(pId, pIntent);
View view = (window != null) ? window.getDecorView() : null;
// Add the old activity to the history
history.add(view);
// Set content view to new activity
setContentView(view);
}
/*
* Go back from previous activity or close application if there is no previous activity
*/
public void back()
{
if(history.size() > 1)
{
// Remove previous activity from history
history.remove(history.size()-1);
// Go to activity
View view = history.get(history.size() - 1);
Activity activity = (Activity) view.getContext();
// "Hack" used to determine when going back from a previous activity
// This is not necessary, if you don't need to redraw an activity when going back
activity.onWindowFocusChanged(true);
// Set content view to new activity
setContentView(view);
}
else
{
// Close the application
finish();
}
}
/*
* Overwrite the back button
*/
@Override
public void onBackPressed()
{
// Go one back, if the history is not empty
// If history is empty, close the application
SettingsActivityGroup.group.back();
return;
}
}
SettingsActivityGroup(CallForwardActivity)的任意子项
public class CallForwardActivity extends ListActivity
{
....
@Override
public void onBackPressed()
{
// Go one back, if the history is not empty
// If history is empty, close the application
SettingsActivityGroup.group.back();
return;
}
}
答案 0 :(得分:2)
因为我认为调用当前所选活动的onBackPressed()是所希望的行为。
值得注意的是,不推荐使用ActivityGroup,但我认为你编写的是&lt; 3.0并且不喜欢使用支持库。
关于您编辑过的问题: 本网站上的另一个问题引用本文作为一个很好的ActivityGroup示例,我同意http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html 这个例子只是在按下后退时调用当前活动的finish(),并让os重新启动上一个活动,这比你正在做的更简单,并且希望有效!您也可以在您的子活动中调用getParent()以避免使用该静态引用(这样看起来更容易读给我!)。