我在onCreate中使用以下代码在操作栏中显示下拉菜单。代码工作正常,它显示下拉菜单并执行我在onNavigationItemSelected中添加的任务。但他只发生一次,即如果我第一次选择菜单项2,Toast显示“Selected”消息并执行asynctask。当我重新选择菜单项2时,没有任何反应!为什么会出现这个问题,我怎么能摆脱这个呢?
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
final LinearLayout mainLayout = (LinearLayout) this
.findViewById(R.id.linearLayout1);
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
if (actions[itemPosition].toString().equals("exit")) {
System.exit(0);
}
if (actions[itemPosition].toString().equals(
"Menu Item 2")) {
Toast.makeText(getApplicationContext(),"Selected" ,Toast.LENGTH_LONG).show();
code="2";
//call to an asynctask
}
return false;
}
};
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
答案 0 :(得分:0)
您需要阅读这些链接然后您的问题将解决您调用菜单项的策略不正确所以请按照这些链接
http://developer.android.com/reference/android/view/MenuItem.html
http://developer.android.com/guide/topics/ui/menus.html
http://www.androidhive.info/2011/09/how-to-create-android-menus/
Handling a Menu Item Click Event - Android
Creating an Options Menu in Android
这些代码对于下拉项目选择项目更有用
代码如上: - 转到Project和res文件夹然后菜单/然后转到菜单项的.xml文件
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/menu_addnew"
android:title="new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android:icon="@drawable/menu_addnew"
android:title="help" />
</menu>
and then in java file you have use this code
public class AndroidMenusActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// Initiating Menu XML file (menu.xml)
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.new_game:
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
Toast.makeText(AndroidMenusActivity.this, "Bookmark is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.help:
Toast.makeText(AndroidMenusActivity.this, "Save is Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}