popmenu的用法

 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的监听方法。

代码如下:

package com.example.popmenuexcercise; 
 
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 { 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        final Button button=(Button) findViewById(R.id.button1); 
        button.setOnClickListener(new OnClickListener() { 
             
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                //第二个参数是该popupmenu将要依附于哪个view上,如果该view下面有空间它就在下面显示,否则在其上面 
                PopupMenu popupMenu=new PopupMenu(getApplicationContext(), button); 
                popupMenu.getMenuInflater().inflate(R.menu.main,popupMenu.getMenu()); 
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 
                     
                    @Override 
                    public boolean onMenuItemClick(MenuItem item) { 
                        // TODO Auto-generated method stub 
                        Toast.makeText(getApplicationContext(), item.getTitle(),1000).show(); 
                        return false; 
                    } 
                }); 
                //最后不要忘了调用show方法 
                popupMenu.show(); 
            } 
        }); 
    } 
 
     
 
}

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