Home » Android » android – using onTouch and onCreateContextMenu at the same time

android – using onTouch and onCreateContextMenu at the same time

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am looking to capture the coordinates of the users touch event (For this I implemented the onTouch method), but I also want to display a context menu when the user touches the screen.

When both the onTouch and onCreateContextMenu methods are used, every touch event is sent to the onTouch method. The onCreateContextMenu method is never called. I guess this is expected. I then tried manually displaying the context menu by calling openContextMenu(v) in the onTouch method, this works, but the menu doesn’t disappear from the screen after the onContextItemSelected(MenuItem item) call. So how can I make this work?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.record_match);
    myCourtView = new MyImageView(getApplicationContext());
    ll = (LinearLayout)findViewById(R.id.linearLayout);
    ll.addView(myCourtView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    registerForContextMenu(myCourtView);
    myCourtView.requestFocus();
    myCourtView.setOnTouchListener(this);

}// End OnCreate


    // Implement the OnClickListener callback
   public boolean onTouch(View v, MotionEvent event) {
      //do something when user interacts with the court view
      myCourtView.processEvent(event);
      openContextMenu(v);
      myCourtView.invalidate();
      return true;
    }//End OnClickListener

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.shot_entry_menu, menu);
}//End onCreateContextMenu

@Override
public boolean onContextItemSelected(MenuItem item) {
  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
  switch (item.getItemId()) {
  case R.id.player_1:
    //do something
    return true;
  case R.id.player_2:
    //do something else
    return true;
  }
  return true;
}//End onContextItemSelected
How to&Answers:

you should return false in onTouch:

True if the listener has consumed the event, false otherwise.

Answer:

For me this solution work:

myCourtView.setOnTouchListener(new OnTouchListener()
    {public boolean onTouch(View v, MotionEvent ev)
        {});

Rest is the same

Answer:

try putting this in public boolean onTouch after return true; registerForContextMenu(this.getListView());