在按钮内添加popUp菜单按钮

时间:2017-06-09 16:37:18

标签: android popup

我只是想在按钮中添加一个弹出菜单,我用XML创建了这个菜单。Desired Figure

我做了足够的研究,但无法找到任何解决方案。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

使用此代码

import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
import android.view.MenuItem;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.PopupMenu;  
import android.widget.Toast;  
public class MainActivity extends Activity {  
Button button1;  

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

          button1 = (Button) findViewById(R.id.button1);  
          button1.setOnClickListener(new OnClickListener() {  

           @Override  
           public void onClick(View v) {  
            //Creating the instance of PopupMenu  
            PopupMenu popup = new PopupMenu(MainActivity.this, button1);  
            //Inflating the Popup using xml file  
            popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());  

            //registering popup with OnMenuItemClickListener  
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {  
             public boolean onMenuItemClick(MenuItem item) {  
              Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();  
              return true;  
             }  
            });  

            popup.show();//showing popup menu  
           }  
          });//closing the setOnClickListener method  
         }  
    }