2017-06-13 89 views
0

首先:我们是Android开发新手,我们有一个练习,我们不明白我们需要做什么。Android OnTouch提供了一个错误

我们需要一个OnTouchListener添加到TouchView中,根据课程的PPT这可以在下面所描述的,但它是不工作来完成:

public class MainActivity extends AppCompatActivity{ 

TouchView touchView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //setContentView(R.layout.activity_main); 
    LinearLayout ll = new LinearLayout(this); 
    ll.setOrientation(LinearLayout.VERTICAL); 
    this.setContentView(ll); 

    float x = 500; 
    float y = 500; 
    float size = 1000; 

    touchView = new TouchView(x,y,size,this); 
    touchView.setOnTouchListener(this); 
    ll.addView(touchView); 
} 

public boolean onTouch(View view, MotionEvent motionEvent){ 
    float x = motionEvent.getX(); 
    float y = motionEvent.getY(); 

    return true; 
} 

随着TouchView中类,如下图所示:

public class TouchView extends View { 

public float x,y,size; 
Paint paint = new Paint(); 

public TouchView(float xcor, float ycor, float sizenum, Context context) { 

    super(context); 
    x = xcor; 
    y = ycor; 
    size = sizenum; 
    paint.setAntiAlias(true); 

} 



@Override 
protected void onDraw(Canvas canvas){ 
    super.onDraw(canvas); 

    paint.setColor(Color.BLUE); 

    canvas.drawCircle(x, y, size, paint); 
} 

public TouchView(Context context, AttributeSet attributeSet){ 

    super(context, attributeSet); 

} 
} 

不幸的是,它不工作,我们完全丧失了如何使它工作。有人可以帮助我们吗?

回答

0
public class MainActivity extends AppCompatActivity implement OnTouchListener { 

    TouchView touchView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //setContentView(R.layout.activity_main); 
     LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(LinearLayout.VERTICAL); 
     this.setContentView(ll); 

     float x = 500; 
     float y = 500; 
     float size = 1000; 

     touchView = new TouchView(x,y,size,this); 
     touchView.setOnTouchListener(this); 
     ll.addView(touchView); 
    } 

    public boolean onTouch(View view, MotionEvent motionEvent){ 
     float x = motionEvent.getX(); 
     float y = motionEvent.getY(); 

     return true; 
    } 

} 
+0

Thankyou这确实解决了我们目前的问题,由于某些原因,当我们早些时候尝试时,这没有奏效。幸运的是,现在,我必须做一些与已经做出的另一个编辑有关的事情。 – josap

+0

有谁知道为什么onTouch会被触发两次,而不是一次点击一次? – josap

+0

因为首先当你按下视图时它会调用'ACTION_DOWN',它会调用'ACTION_UP'从视图中取下你的手指 –

相关问题