Search code examples
androidbuttoncontextmenuonlongclicklistener

Setting ContextMenu on SetOnLongClickListener


How can I set my app to show Context Menu on Long Click Listener? I want it when I click to play sound, and on long click to show menu with some options and buttons, on 1 same button. So I want o normal click to play sound, on long click to show menu with some buttons which I can use to set as ringtone and other stuff.

mp=MediaPlayer.create(this, R.raw.hekler);

ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {


    if (mp2.isPlaying()){
        mp2.pause();
        mp2.seekTo(0);
    }

    else{
        mp.start();
    }

}

});

btn1.setOnLongClickListener(new OnLongClickListener() {
    public boolean onLongClick(View arg0) {       
        return true;
    }
});

Solution

  • To show a context menu on long click, you should call registerForContextMenu(View) for view that is clicked.

    You should also override onCreateContextMenu(ContextMenu, View, ContextMenu.ContextMenuInfo)

    You not need setOnLongClickListener. If you need it for some other reason, it should return false.

    In your code:

    ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
    registerForContextMenu(btn1);
    
    btn1.setOnClickListener(new View.OnClickListener() {
    
        -------------
        -------------
    
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                super.onCreateContextMenu(menu, v, menuInfo);
    
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.your_context_menu, menu);
    }
    

    To handle the context menu:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
            case R.id.contextItem1:
                //Do what you want
            return true;
    
            case R.id.contextItem2:
                //Do what you want
            return true;
    
            default:
                return super.onContextItemSelected(item);
        }
    }