晚上好
我是android studio的新手,只是在网上关注随机项目。我已经编写了这个简单的游戏。它将在屏幕上绘制一个红色圆圈,每次您在屏幕上点击时,它将在屏幕的新区域中随机生成一个圆圈。尝试更新Textview时,我正在寻求帮助。文本视图的目的是跟踪圈子中的匹配数。但是,当我找到textview时,加载后应用程序将崩溃。如何在不使应用程序崩溃的情况下更新textview?
public class MainActivity extends AppCompatActivity {
//If I remove this line of code the application will not crash.
TextView score = findViewById(R.id.scoreTextView);
Paint paint;
Path path;
int counter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View {
Paint paint;
Path path;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
float maxx = getWidth();
float maxy = getHeight();
float x;
float y;
float allowablex;
float allowabley;
int radius = 100;
//random here
Random rand = new Random();
x = rand.nextInt((int) (maxx - 1));
y = rand.nextInt((int) maxy - 1);
allowablex = maxx - x;
allowabley = maxy - y;
if (allowablex > 0) {
if (allowabley > 0) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#da4747"));
canvas.drawCircle(x, y, radius, paint);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
counter++;
break;
case MotionEvent.ACTION_UP:
counter++;
break;
case MotionEvent.ACTION_MOVE:
counter++;
break;
}
invalidate();
return super.onTouchEvent(event);
}
}
}