其他分享
首页 > 其他分享> > Android 弹出式菜单 绑定到按钮

Android 弹出式菜单 绑定到按钮

作者:互联网

在按钮上绑定弹出菜单就可以实现点击按钮下拉菜单的效果

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 为这个按钮绑定弹出菜单
        final Button btn = findViewById(R.id.btn);

        // 长按时显示弹出菜单
        btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 初始化菜单
                PopupMenu popupMenu = new PopupMenu(MainActivity.this, btn);
                
                // 将菜单视图文件绑定到popupMenu的menu对象上
                popupMenu.getMenuInflater().inflate(R.menu.first, popupMenu.getMenu());
                
                // 注册菜单项监听器
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.login:
                                Toast.makeText(MainActivity.this, "你刚刚点了登录", Toast.LENGTH_LONG).show();
                                break;
                            case R.id.register:
                                Toast.makeText(MainActivity.this, "你刚刚点了注册", Toast.LENGTH_LONG).show();
                                break;
                        }
                        return false;
                    }
                });
                
                // 显示菜单
                popupMenu.show();
                return true;
            }
        });
    }
}

标签:Toast,菜单,绑定,popupMenu,MainActivity,Android,btn,弹出式
来源: https://www.cnblogs.com/esrevinud/p/12112995.html