您好我有一个主类whic设置一个新的View它是我制作的绘画类,在其中我有一个从另一个类绘制一个Rectangle的ondraw方法。我希望能够通过触摸屏幕移动矩形,所以我会使用ontouchlistener,但它似乎无论在我点击屏幕或在模拟器上拖动我的鼠标矩形不移动似乎无法正常工作?< / p>
// 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);
}
}
答案 0 :(得分:1)
您没有关联在onCreate()中实现的OnTouchListener。你指的是Main的一些OnTouchListener。因此,您没有执行在绘画中实现的onTouch方法。
答案 1 :(得分:0)
添加“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);”来自活动课。