Android OnTouchListener实时监听触点坐标,需要同时监听OnClickListener才有效

public class TouchTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        final TextView tv=new TextView(this);
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(15);
        
        LinearLayout view=new LinearLayout(this);
        view.setBackgroundColor(Color.WHITE);
        view.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				tv.setText("rawx="+String.valueOf(arg1.getRawX())+"rawy="+String.valueOf(arg1.getRawY())+"\n");
				tv.append("x="+String.valueOf(arg1.getX())+"y="+String.valueOf(arg1.getY())+"\n");
				//tv.append("0x="+String.valueOf(arg1.getX(0)+"0y="+String.valueOf(arg1.getY(0))+"\n");
				
				int action =arg1.getAction();
				if(action==MotionEvent.ACTION_MOVE){
					System.out.println("yidong");
				}
				if(action==MotionEvent.ACTION_DOWN){
					System.out.println("down");
				}
				if(action==MotionEvent.ACTION_UP){
					System.out.println("up");
				}
				if(action==MotionEvent.ACTION_CANCEL){
					System.out.println("cancel");
				}
				
				return false;
			}
        	
        });
        /*
         * 如果没有onClickListener,那么触笔在移动时,上面的只有down事件,其他都不会触发
         * 而如果添加了,则move和up事件都会相应
         * 
         */
        view.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
			}
        	
        });
        
        view.addView(tv);
        setContentView(view);
    }
}

发布了99 篇原创文章 · 获赞 54 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/mrlixirong/article/details/8435529