PopupMenu的用法

 PopupMenu是用来在其所指定的view上显示菜单,用法很简单:

1.PopupMenu popupmenu = new PopupMenu(this,target view); 

它要绑定在谁身上,target view 就是谁

2.加载出该菜单

popupMenu.getMenuInflater().inflate(R.menu.main,popupMenu.getMenu());

3.显示该popupmenu

popupmenu.show();

另外popupmenu有点击menuItem的监听方法。

代码如下:

  
  
  
  
  1. package com.example.popmenuexcercise; 
  2.  
  3. import android.os.Bundle; 
  4. import android.app.Activity; 
  5. import android.view.Menu; 
  6. import android.view.MenuItem; 
  7. import android.view.View; 
  8. import android.view.View.OnClickListener; 
  9. import android.widget.Button; 
  10. import android.widget.PopupMenu; 
  11. import android.widget.Toast; 
  12.  
  13. public class MainActivity extends Activity { 
  14.  
  15.     @Override 
  16.     protected void onCreate(Bundle savedInstanceState) { 
  17.         super.onCreate(savedInstanceState); 
  18.         setContentView(R.layout.activity_main); 
  19.         final Button button=(Button) findViewById(R.id.button1); 
  20.         button.setOnClickListener(new OnClickListener() { 
  21.              
  22.             @Override 
  23.             public void onClick(View v) { 
  24.                 // TODO Auto-generated method stub 
  25.                 //第二个参数是该popupmenu将要依附于哪个view上,如果该view下面有空间它就在下面显示,否则在其上面 
  26.                 PopupMenu popupMenu=new PopupMenu(getApplicationContext(), button); 
  27.                 popupMenu.getMenuInflater().inflate(R.menu.main,popupMenu.getMenu()); 
  28.                 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 
  29.                      
  30.                     @Override 
  31.                     public boolean onMenuItemClick(MenuItem item) { 
  32.                         // TODO Auto-generated method stub 
  33.                         Toast.makeText(getApplicationContext(), item.getTitle(),1000).show(); 
  34.                         return false
  35.                     } 
  36.                 }); 
  37.                 //最后不要忘了调用show方法 
  38.                 popupMenu.show(); 
  39.             } 
  40.         }); 
  41.     } 
  42.  
  43.      
  44.  

 

你可能感兴趣的:(popupmenu的用法)