gpt4 book ai didi

安卓延迟文本

转载 作者:行者123 更新时间:2023-11-30 02:35:07 25 4
gpt4 key购买 nike

我想将文本设置为 25 个按钮,但每个文本在 5 秒后出现。我尝试过使用大量不同的方法。我尝试使用 Thread.sleep(5000) 但我的程序崩溃了。然后我试图创建一个处理程序,但它崩溃了。有人可以告诉我为什么吗?或者还有另一种我应该延迟文本的方式:

*注意:在我的代码中,我使用了 findViewById 方法,但为了简单和重复起见,我决定不在此处发布它——所以这不是问题所在。

public class Game extends Activity {

protected List<String> my_list = new ArrayList<String>();
protected String letters[];
protected List<Button> button_list = new ArrayList<Button>();
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10,
b11, b12, b13, b14, b15, b16, b17, b18, b19, b20,
b21, b22, b23, b24;

Random rand = new Random();
int random_counter;
int my_list_counter = 25;
int i;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
letters = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y"};
Button[] bttn_arr = new Button[] {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10,
b11, b12, b13, b14, b15, b16, b17, b18, b19, b20,
b21, b22, b23, b24};


my_list.addAll(Arrays.asList(letters));

button_list.addAll(Arrays.asList(bttn_arr));

final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for (i=0; i<25; i++){
random_counter = rand.nextInt(my_list_counter);
button_list.get(i).setText(my_list.get(random_counter));
my_list.remove(my_list.get(random_counter));
my_list_counter--;
handler.postDelayed(this, 5000);
}
}
});
}

最佳答案

尝试改用它:

for (int i = 0; i < 20; i++) {
final String message = "Hello" + i;
Runnable x = new Runnable(){
@Override
public void run(){
Log.i("Hello", message);

}
};

Handler handler = new Handler();
//Run the code in runnable x at increasing time intervals of 5 seconds
handler.postAtTime(x, SystemClock.uptimeMillis() + i*5000);

}

}


此代码将每 5 秒打印一次“hello”+ i(例如 hello1 然后 hello2 然后 hello3 等)。如果你调整你的代码,它将每 5 秒运行一次。在之前的实例中,处理程序一次发布并运行所有可运行对象,现在它一次发布所有可运行对象,除了每个开始时间增加 5 秒(参见 handler.postAtTime(...) )。希望这对您有所帮助!

关于安卓延迟文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26696175/

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