弹出式菜单
1、调用new PopupMenu(Context context,View anchor)创建下拉菜单,anchor代表要激发该弹出菜单的组件
2、调用MenuInflater的inflate()方法将菜单资源填充到PopupMenu中
turn super.onOptionsItemSelected(item);
}
return true;
}
}
弹出式菜单
1、调用new PopupMenu(Context context,View anchor)创建下拉菜单,anchor代表要激发该弹出菜单的组件
2、调用MenuInflater的inflate()方法将菜单资源填充到PopupMenu中
3、调用PopupMenu的show()方法显示弹出式菜单
package com.example.myapplication; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.view.menu.MenuPopupHelper; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Button; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView; import android.widget.Toast; import java.lang.reflect.Field; import java.lang.reflect.Method; public class MainActivity extends AppCompatActivity { //定义按钮的全局变量 private Button button; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 绑定按钮的资源(利用id找到xml文件中的按钮) button = findViewById(R.id.button); textView = findViewById(R.id.textView); registerForContextMenu(textView); button.setOnClickListener(new View.OnClickListener() { @SuppressLint("RestrictedApi") @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onClick(View v) { //创建PopupMenu PopupMenu popupMenu = new PopupMenu(MainActivity.this,button); //加载菜单资源 popupMenu.getMenuInflater().inflate(R.menu.menu2, popupMenu.getMenu()); //菜单事件监听 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.bu1: Toast.makeText(MainActivity.this,"复制",Toast.LENGTH_LONG).show(); break; case R.id.bu2: Toast.makeText(MainActivity.this,"粘贴",Toast.LENGTH_LONG).show(); break; case R.id.bu3: Toast.makeText(MainActivity.this,"清除",Toast.LENGTH_LONG).show(); break; default: break; } return true; } }); //使用反射,强制显示菜单图标 try { Field field = popupMenu.getClass().getDeclaredField("mm"); field.setAccessible(true); MenuPopupHelper menuPopupHelper = (MenuPopupHelper) field.get(popupMenu); menuPopupHelper.setForceShowIcon(true); }catch (IllegalAccessException | NoSuchFieldException e){ e.printStackTrace(); } popupMenu.show(); } }); } }
关于Java代码有很多包名,如果有哪个方法没有找到什么包可以 “Alt+Enter”快捷键帮你找到这个地方的可能需要要导入的包或者其他。
整个代码的引入是从第一个写到最后一个菜单的累加的。