gpt4 book ai didi

java - 我的 onClickListener 有什么问题?

转载 作者:行者123 更新时间:2023-12-01 16:50:30 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的应用程序,它显示一个彩色圆圈,当它远离屏幕中心时,该圆圈会逐渐变成黑色。但是,每当我单击该应用程序时,它就会崩溃。当我删除 onClick 代码时,应用程序运行正常。我在 logcat 中找到的唯一错误是:

Fatal signal 11 (SIGSEGV), code 1, fault addr 0x94 in tid 11955 (raphicstutorial)

我不知道该怎么办。

代码如下:

package com.example.a2dgraphicstutorial;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends AppCompatActivity {
public class MyView extends View {
private Canvas thisCanvas;
private int colourID;
private Paint fillPaint = new Paint();

public MyView(Context context){
super(context);
colourID = 0;
fillPaint.setStyle(Paint.Style.FILL);
}

public void drawCircle(){
int x = getWidth();
int y = getHeight();

//Drawing the circles
for (int i = 255;i >= 0;i--){
//Determining colour
if (colourID == 0){
fillPaint.setColor(Color.argb(255,255-i,0,0));
}
else if (colourID == 1){
fillPaint.setColor(Color.argb(255,0,255-i,0));
}
else if (colourID == 2){
fillPaint.setColor(Color.argb(255,0,0,255-i));
}

thisCanvas.drawCircle(x/2,y/2,i,fillPaint);
}

//Cycling the colourID so the next circle will be a different colour
colourID = (colourID + 1)%3;
}

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

//Setting the background to be black
fillPaint.setColor(Color.parseColor("#000000"));
thisCanvas.drawPaint(fillPaint);

//Drawing the first circle
drawCircle();
}

}
MyView theScreen;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = new MyView(this);
theScreen.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
theScreen.drawCircle();
}
});

setContentView(theScreen);
}
}

最佳答案

而不是重写onCreate()

重写onTouchEvent()并监听点击:

@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//the finger is down do something.....

return true;

case MotionEvent.ACTION_UP:
//the finger is up do something.....(this is a click)
//to redraw
invalidate();

return true;
}
return false;
}

顺便说一句:

要触发 onDraw(),请在单击后调用:

invalidate();

关于java - 我的 onClickListener 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61700168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com