点击操作栏按钮后,我有一个弹出菜单。当我点击操作栏按钮时,我正在弹出窗口。但我想打开另一个单击弹出菜单项的活动。我怎么能这样做?
以下是我的代码段。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@SuppressLint("NewApi") @Override
public boolean onOptionsItemSelected(MenuItem item) {
View menuItemView = findViewById(R.id.action_button);
PopupMenu popupMenu = new PopupMenu(this, menuItemView);
popupMenu.inflate(R.menu.popup);
popupMenu.show();
return true;
}
我的弹出菜单如下,
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<item
android:id="@+id/one"
android:title="About"
android:visible="true"
android:showAsAction="ifRoom|withText"/>
<item
android:id="@+id/two"
android:title="Contact Us"
android:visible="true"
android:showAsAction="ifRoom|withText"/>
</menu>
我想要做的是,当我点击这些菜单项时,必须打开另一个活动。我怎么能这样做? 有谁可以帮助我吗。提前谢谢。
答案 0 :(得分:1)
使用id使用带有menuId
的switch语句启动活动 @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.one:
Intent intent1 =new Intent(this,ActivityOne.class);//firstActivity
startActivity(intent1);
return true;
case R.id.two:
Intent intent2 =new Intent(this,ActivityTwo.class);//second Activity
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
答案 1 :(得分:0)
要在弹出菜单上打开活动,请单击:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item1:
Intent intent = new Intent(this, ActivityForItemOne.class);
this.startActivity(intent);
break;
case R.id.menu_item2:
// another startActivity, this is for item with id "menu_item2"
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
答案 2 :(得分:0)
试试这个
popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});