这是我上周发布的一个问题的跟进(Option Menu not opening from ListActivity when list is empty。)我已经做了一些工作来缩小我一直存在的问题。选项菜单的问题相当复杂,不适合胆小的人。
我的项目使用ListActivity作为选项菜单。 ListActivity从活动组中启动。 (我在一个活动组中使用它,这样“后退”按钮就能正常工作,以便在特定标签内的活动中向后移动。)
只要为列表提供了数据,选项菜单就能完美运行。但是,如果没有数据,选项菜单按钮将不会触发选项菜单。
但是,选项菜单适用于具有空列表的ListActivity,前提是ListActivity不是从ActivityGroup中启动的。
为了重新创建问题,我使用从ActivityGroup类(TabsFirstGroup)中启动的ListActivity类(MsgList)创建了一个非常精简的示例。
如果我在MsgList中注释掉第30行(我填充了为列表提供数据的数组words.add(s);
),则选项菜单将无法实例化。我从未到达MsgList中的onCreateOptionsMenu()方法,这是通过设置一个永不命中的调试断点来推断的。
这是TabsFirstGroup类: 包com.techmeridian.testframework;
import java.util.ArrayList;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class TabsFirstGroup extends ActivityGroup {
// Keep this in a static variable to make it accessible for all the nesten activities, lets them manipulate the view
public static TabsFirstGroup 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);
this.history = new ArrayList<View>();
group = this;
View view = getLocalActivityManager().startActivity("MsgListActivity", new
Intent(this,MsgList.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
}
public void replaceView(View v) {
// Adds the old one to history
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}
public void back() {
if(history.size() > 0) {
history.remove(history.size()-1);
setContentView(history.get(history.size()-1));
}else {
finish();
}
}
@Override
public void onBackPressed() {
TabsFirstGroup.group.back();
return;
}
}
这是MsgList类:
package com.techmeridian.testframework;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.ArrayAdapter;
public class MsgList extends ListActivity {
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet", "consectetuer", "adipiscing", "elit",
"morbi", "vel", "ligula", "vitae", "arcu", "aliquet",
"mollis", "etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
private ArrayList<String> words=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
words=new ArrayList<String>();
for (String s : items) {
// IF I COMMENT THE NEXT LINE OUT, THEN THE OPTION MENU WILL NOT WORK!
words.add(s);
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, words));
registerForContextMenu(getListView());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
}
非常感谢任何帮助。感谢。