同时使用onTouch和onCreateContextMenu

时间:2011-05-03 00:03:23

标签: android

我希望捕获用户触摸事件的坐标(为此我实现了onTouch方法),但我还希望在用户触摸屏幕时显示上下文菜单。

当使用onTouchonCreateContextMenu方法时,每个触摸事件都会发送到onTouch方法。永远不会调用onCreateContextMenu方法。我想这是预料之中的。然后我尝试通过openContextMenu(v)方法调用onTouch来手动显示上下文菜单,这样可行,但在onContextItemSelected(MenuItem item)调用后菜单不会从屏幕上消失。那么我怎样才能做到这一点呢?

@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

3 个答案:

答案 0 :(得分:0)

你应该在onTouch中返回false:

如果监听器已经使用了该事件,则为true,否则为false。

答案 1 :(得分:0)

对我来说,这个解决方案有效:

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

休息是一样的

答案 2 :(得分:0)

在返回true之后尝试将它放在公共布尔值onTouch中; registerForContextMenu(this.getListView());