gpt4 book ai didi

android - 编译运行但崩溃

转载 作者:行者123 更新时间:2023-12-03 16:51:27 25 4
gpt4 key购买 nike

因此,我正在尝试编写代码,该代码每5秒会在屏幕上的随机位置产生一个红色圆圈。我编写了代码,该代码仅会产生一个红色圆圈,而不会每5秒重复一次,因此效果很好。然后,当我添加代码(注释掉)以每5秒绘制另一个圆圈时,该程序仍会编译并运行,但立即在我的测试电话上崩溃了。这是代码。

public class RandomCircles extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Timer timer = new Timer();
// timer.scheduleAtFixedRate(new TimerTask() {
// public void run() {
setContentView(new MyView(RandomCircles.this));
// }
// }, 0, 5 * 1000L);//5 seconds
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_random_circles, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

class MyView extends View {
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
//800, 1162
Random rand = new Random();
x = rand.nextInt(getWidth());

if(getWidth() - x < 100)
x -= 100;
else if(getWidth() - x > getWidth() - 100)
x += 100;

int y = rand.nextInt(getHeight());

if(getHeight() - y < 100)
y -= 100;
else if(getHeight() - x > getHeight() - 100)
y += 100;

int radius;
radius = 100;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x, y, radius, paint);
}
}

这是logcat:

最佳答案

通常,涉及用户界面的任何操作都必须在主线程或UI线程中完成,因此,您不能在任何其他线程上执行与用户界面相关的任何操作。
您可以通过以下方式使用TimerTask,

Timer timer = new Timer();
timer.scheduleAtFixedRate( new TimerTask() {

@Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
setContentView(new MyView(MainActivity.this));
}
});
}
}, 0, 5 * 1000L);

而且不要忘了读这篇
Activity.runOnUiThread

关于android - 编译运行但崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873065/

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