在Android中的SDK3.0版本以后加入了一个特殊的菜单效果,它可以在任何的View上显示,根据View的位置显示菜单效果。
res/menu/menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/send" android:title="发送邮件"></item>
<item android:id="@+id/look" android:title="阅读邮件"></item>
<item android:id="@+id/delete" android:title="删除邮件"></item>
</menu>
MainActivity.java
package com.zhangyu.mypopupmenu;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
private TextView tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myPopupMenu(v);
}
});
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myPopupMenu(v);
}
});
tv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myPopupMenu(v);
}
});
}
private void myPopupMenu(View v) {
//定义PopupMenu对象
PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
//设置PopupMenu对象的布局
popupMenu.getMenuInflater().inflate(R.menu.menu, popupMenu.getMenu());
//设置PopupMenu的点击事件
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "点击了----" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
//显示菜单
popupMenu.show();
}
}
来源:CSDN
作者:张雨明
链接:https://blog.csdn.net/yu540135101/article/details/103652910