在我的活動,我有兩個圖標按鈕,在action bar
如何獲得2個選項選項?
這是add_task.xml
<item
android:id="@+id/action_add_task"
android:icon="@drawable/create_new"
android:title="Add New"
app:showAsAction="always" />
<item
android:id="@+id/menu"
android:icon="@drawable/menu"
android:title="Menu"
app:showAsAction="always" />
當點擊該圖標menu
,我得到這個
popup.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/opt1"
android:icon="@drawable/change_pic"
android:title="Change Profile" />
<item
android:id="@+id/opt2"
android:icon="@drawable/sign_out"
android:title="Sign Out" />
</menu>
我的問題是,當menu
圖標點擊Toast
得到顯示。我只希望它在點擊更改配置文件時顯示。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_task, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
View menuItemView = findViewById(R.id.menu);
MenuBuilder menuBuilder =new MenuBuilder(this);
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.popup, menuBuilder);
MenuPopupHelper optionsMenu = new MenuPopupHelper(this, menuBuilder, menuItemView);
optionsMenu.setForceShowIcon(true);
optionsMenu.show();
case R.id.opt1: // when change profile clicked
Toast.makeText(getApplication(),"Profile",Toast.LENGTH_SHORT).show();
default:
return super.onOptionsItemSelected(item);
}
}
編輯
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
View menuItemView = findViewById(R.id.menu);
MenuBuilder menuBuilder = new MenuBuilder(this);
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.popup, menuBuilder);
final MenuPopupHelper optionsMenu = new MenuPopupHelper(this, menuBuilder, menuItemView);
opionsMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if ("Change Profile".equals(item.getTitle())) {
Intent intent = new Intent(AddMonthlyExpenses.this, Profile.class); // go to Information class
intent.putExtra("name", name);
startActivity(intent);
}
optionsMenu.setForceShowIcon(true);
optionsMenu.show();
return true;
}
});
default:
return super.onOptionsItemSelected(item);
}
return true;
}
我就在這行
opionsMenu.setOnMenuItemClickListener
optionsMenu不能得到解決的錯誤。
'opionsMenu'!='optionsMenu' ..there是一個錯字您的代碼.. – n0rph3u5
如果add_task在菜單文件夾中,那麼根標籤必須是* menu * –