2013-05-08 40 views
0

我試圖顯示一個敬酒當用戶長按android屏幕....但沒有顯示。爲什麼?簡單的觸摸顯示吐司「觸摸」工作正常!錯誤在哪裏?長按安卓事件的錯誤

public class MainActivity extends Activity { 
    Handler handler = new Handler(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);  
} 

Runnable mLongPressed = new Runnable() { 
    public void run() { 
     Toast.makeText(getBaseContext(), 
       "Long press", 
       Toast.LENGTH_LONG).show(); 
    } 
}; 

@Override 
public boolean onTouchEvent(MotionEvent event){ 
    if(event.getAction() == MotionEvent.ACTION_DOWN) 
     Toast.makeText(getBaseContext(), 
       " touch ", 
       Toast.LENGTH_LONG).show(); 
     handler.postDelayed(mLongPressed, 1000); 
    if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP)) 
     handler.removeCallbacks(mLongPressed); 
    return super.onTouchEvent(event); 
} 

回答

0

段:

public class MainActivity extends Activity implements OnLongClickListener { 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);  

    View yourView = (View) findViewById(R.id.longclickview); 
    yourView.setOnLongClickListener(this); 
} 

@Override 
public boolean onLongClick(View v) { 
    Toast.makeText(getBaseContext(), 
      "Long press", 
      Toast.LENGTH_LONG).show(); 
    return false; 
} 
1

您應該使用GestureDetector確定長按,如下所示:

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { 
     public void onLongPress(MotionEvent e) { 
      Toast.makeText(getBaseContext(), "Long press", Toast.LENGTH_LONG).show(); 
     } 
    }); 

    public boolean onTouchEvent(MotionEvent event) { 
     return gestureDetector.onTouchEvent(event); 
    };