Android PopupMenu-点击按钮弹出下拉框

1.建立一个xml文件作为下拉框界面



 
    
    
    

2.然后在Java文件中

package com.example.menutest03;
 
import android.app.Activity;import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
 
 
public class MainActivity extends Activity implements OnClickListener,OnMenuItemClickListener{
 
    
    private Button button1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(this);
    }
 
    //点击按钮后,加载弹出式菜单
    @Override
    public void onClick(View v) {
        //创建弹出式菜单对象(最低版本11)
        PopupMenu popup = new PopupMenu(this, v);//第二个参数是绑定的那个view
        //获取菜单填充器
        MenuInflater inflater = popup.getMenuInflater();
        //填充菜单
        inflater.inflate(R.menu.main, popup.getMenu());
        //绑定菜单项的点击事件
        popup.setOnMenuItemClickListener(this);
        //显示(这一行代码不要忘记了)
        popup.show(); 
        
    }
 
    //弹出式菜单的单击事件处理
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.exit:
            Toast.makeText(this, "退出", Toast.LENGTH_SHORT).show();
            break;
        case R.id.set:
            Toast.makeText(this, "设置", Toast.LENGTH_SHORT).show();
            break;
        case R.id.account:
            Toast.makeText(this, "账号", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
        return false;
    }
    
}

转载自:https://blog.csdn.net/xch_yang/article/details/80585041?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

你可能感兴趣的:(android)