package com.example.myball;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawView extends View{
float x=40;
float y=50;
//定义一个画笔
Paint p;
public DrawView(Context context){
super(context);
}
public DrawView(Context context, AttributeSet set){
super(context,set);
}
public void onDraw(Canvas canvas){
super.onDraw(canvas);
p.setColor(Color.BLACK);
canvas.drawCircle(x, y, 15, p);
}
public boolean onTouchEvent(MotionEvent event){
x=event.getX();
y=event.getY();
invalidate();
return true;
}
}
////
package com.example.myball;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.LinearLayout;
public class BallActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ball);
LinearLayout root = (LinearLayout) findViewById(R.id.root);
final DrawView draw = new DrawView(this);
draw.setMinimumHeight(300);
draw.setMinimumWidth(400);
root.addView(draw);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.ball, menu);
return true;
}
}
这个是让一个小球移动。我有几个问题就直接问了啊
public DrawView(Context context){
super(context);
}
public DrawView(Context context, AttributeSet set){
super(context,set);
}
这里我不知道是什么意思?求帮忙讲解。
LinearLayout root = (LinearLayout) findViewById(R.id.root);
还有这里,总是说我R.id里没有root 可是我已经添加了啊。总是报错。
------解决方案--------------------
activity_ball.xml中有id为root的LinearLayout 吗?有的话再clean下试试