gpt4 book ai didi

java - 5000 毫秒后在 ImageView 中显示数组中的随机图像

转载 作者:行者123 更新时间:2023-11-30 10:49:15 25 4
gpt4 key购买 nike

我有一个字符串数组,它在按下按钮后 5000 毫秒后在 TextView 中显示随机文本结果。我想要实现的是拥有一组图像而不是文本,因此希望在 5000 毫秒后在 ImageView 中显示随机图像。

public class MainActivity extends AppCompatActivity {
private ImageView thumbPrint;
private TextView result;
private AnimationDrawable thumbAnimation;
private String[] moodResults;
private Runnable mRunnable;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);

moodResults = new String[]{
"result a",
"result b",
"result c",
"result d",
"result e",
"result f"
};

thumbPrint = (ImageView)findViewById(R.id.thumbPrint);
thumbPrint.setBackgroundResource(R.drawable.thumb_animation);
thumbAnimation = (AnimationDrawable)thumbPrint.getBackground();

result = (TextView)findViewById(R.id.resultText);

thumbPrint.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
thumbAnimation.start();
showResult();
return true;
}
});
}

public void showResult(){
mRunnable = new Runnable() {
@Override
public void run() {
int rand = (int)(Math.random()* moodResults.length);
result.setText(moodResults[rand]);
//stop animation
thumbAnimation.stop();
}
};

Handler mHandler = new Handler();
mHandler.postDelayed(mRunnable, 5000);
}
}

最佳答案

这样实现:

这些变量在 MainActivity 中声明。它们可以在 onCreate()

中单独初始化
 final int[] imageIds= {
R.drawable.image1, R.drawable.image2, ...}; // This is your array with resource id of each image
Random r = new Random();
Handler mHandler = new Handler();

这是 showResult() 的重构代码:

public void showResult(){
mRunnable = new Runnable() {
@Override
public void run() {
int rand = (int)(Math.random()* moodResults.length);
result.setText(moodResults[rand]);
int randomInt = r.nextInt(imageIds.length);
thumbprint.setBackgroundResource(imageIds[randomInt]); //thumbprint is your Imageview
//stop animation
thumbAnimation.stop();
mHandler.postDelayed(mRunnable, 5000);//This causes hanlder to called again in 5 seconds
}
};

mHandler.postDelayed(mRunnable, 5000); //Here handler is called the first time; the code in mRunnable will execute after 5 seconds
}

关于java - 5000 毫秒后在 ImageView 中显示数组中的随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35477432/

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