gpt4 book ai didi

java - 在添加和删除 TextView 之间暂停程序

转载 作者:行者123 更新时间:2023-12-01 23:27:21 26 4
gpt4 key购买 nike

我正在开发一款坦克游戏,我有一个代表射击的 TextView 。现在我想在特定点显示 TextView ,并在一秒钟后将其删除,看起来镜头一步一步走得更远。但是,当我添加倒计时或 Thread.sleep 时,程序会停止一秒钟,但 TextView 不会消失。我想将 TextView 移动到屏幕上,并且在 for 循环的每次迭代之后我想等待一秒钟,然后再次重新排列它?

这是代码:

 public void shot(float power, float winkel, Button button) {

if(winkel>90) {
winkel = winkel - 10;
}else if(winkel<90){
winkel = winkel +10;
}
for (double i = 0; i<100;i = i+ 1) {

final TextView textView = new TextView(context);
textView.setText(".");
double x = tanks.get(currentTank).getxPos()+(i*power*Math.cos(winkel *(Math.PI/180)));
double y = tanks.get(currentTank).getyPos()+(-1*(i*power*Math.sin(winkel *(Math.PI/180))));
double gravity = (-1*((9.81/2)*Math.pow(i,2)));
y = (y-gravity);
textView.setX((float) x);
textView.setY((float) y);
layout.addView(textView);



for (int j = 0;j<tanks.size();j++){
if(textView.getX()>tanks.get(j).getxPos()&&textView.getX()<tanks.get(j).getxPos()+100){
if(textView.getY()>tanks.get(j).getyPos()&&textView.getY()<tanks.get(j).getyPos()+100){

float k = tanks.get(j).getxPos()-textView.getX();
if(k<0){
k = k*-1;
}
makeDamage(k,tanks.get(j));
}
}
}
new CountDownTimer(2000,1000){

@Override
public void onTick(long millisUntilFinished) {

}
@Override
public void onFinish() {
layout.removeView(textView);
}
}.start();
}
newTurn();
}

我想在添加 TextView 一秒钟后暂停程序并将其删除。程序停止,但 TextView 不会消失,直到 for 循环完成。然后所有 TextViews 消失。

问题已解决:我已经添加了数组中的所有位置,然后是这个

public void drawShot(final Button firework, final ArrayList<TextView> toDraw){
final int[] i = {0};
final Handler mHandler = new Handler();

firework.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onClick(View v) {
firework(firework,toDraw.get(i[0]).getX(),toDraw.get(i[0]).getY());
}
});


Runnable runnable = new Runnable() {
@Override
public void run() {

layout.addView(toDraw.get(i[0]));
if(!check(toDraw.get(i[0]))) {
mHandler.postDelayed(this, (long) 1);
}
i[0]++;

}
};

// start it with:
mHandler.post(runnable);

}

最佳答案

可能需要在主线程上运行删除命令

Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
@Override
public void run() {
layout.removeView(textView);
}
};
mainHandler.post(myRunnable);

关于java - 在添加和删除 TextView 之间暂停程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302625/

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