码迷,mamicode.com
首页 > 移动开发 > 详细

Android 点击按钮弹出菜单

时间:2019-09-23 18:18:43      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:XML   extends   OLE   end   override   菜单   void   弹出菜单   bundle   

效果图:

技术图片

 

 

1、创建menu文件夹,新建main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/add"
android:title="添加" />
<item
android:id="@+id/remove"
android:title="删除" />
<item
android:id="@+id/share"
android:title="分享" />
</menu>

2、在MainActivity 中
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageVie = findViewById(R.id.main_img);
imageVie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupMenu(imageVie);
}
});
}

private void showPopupMenu(View view) {
// View当前PopupMenu显示的相对View的位置
PopupMenu popupMenu = new PopupMenu(this, view);
// menu布局
popupMenu.getMenuInflater().inflate(R.menu.main, popupMenu.getMenu());
// menu的item点击事件
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
return false;
}
});
// PopupMenu关闭事件
popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
}
});

popupMenu.show();
}
}

Android 点击按钮弹出菜单

标签:XML   extends   OLE   end   override   菜单   void   弹出菜单   bundle   

原文地址:https://www.cnblogs.com/guochangxin/p/11573707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!