![](/img/trans.png)
[英]Where do I put the onTouchListener method in an android project?
[英]OnTouch doesnt work where do I have to put the onTouchlistener
您好,所以我有一个主类,它设置了一个新的View,它是我制作的绘画类,并且其中有一个ondraw方法,该方法从另一个类中绘制一个Rectangle。 我希望能够通过触摸屏幕来移动矩形,所以我会使用ontouchlistener,但是无论我单击屏幕还是在模拟器上拖动鼠标,矩形都不会移动,该方法似乎无法正常工作我该如何纠正呢?
// Painting class
public class Painting extends View implements OnTouchListener{
myRectangle player = new myRectangle();
public Painting(Context context) {
super(context);
// TODO Auto-generated constructor stub
DisplayMetrics dm = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
player.size = (int) (dm.widthPixels / 7.5);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
player.drawBlock(canvas);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
player.xpos = (int) event.getX();
player.ypos = (int) event.getY();
return false;
}
}
我的主班:
public class Main extends Activity {
Painting v;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
v = new Painting(Main.this);
v.setOnTouchListener((OnTouchListener) Main.this);
setContentView(v);
}
这是我的Rectangle类:
public class myRectangle{
public int size;
public int xpos;
public double ypos;
public int instrY;
private Paint paint = new Paint();
public myRectangle(){
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#34495E"));
}
public void drawBlock(Canvas c){
c.drawRect(xpos, (float) ypos, size, size, paint);
}
}
您没有关联要在onCreate()中实现的OnTouchListener。 您指的是Main的一些OnTouchListener。 因此,您不执行在绘画中实现的onTouch方法。
添加“ setOnTouchListener(this);” 内部绘画课。
像下面的代码一样,
// Painting class
public class Painting extends View implements OnTouchListener{
myRectangle player = new Rectangle();
public Painting(Context context) {
super(context);
// TODO Auto-generated constructor stub
DisplayMetrics dm = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
player.size = (int) (dm.widthPixels / 7.5);
setOnTouchListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
player.drawBlock(canvas);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
player.xpos = (int) event.getX();
player.ypos = (int) event.getY();
return false;
}
并删除行“ v.setOnTouchListener((OnTouchListener)Main.this);” 从活动类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.