我有一个字符串数组,在按下按钮后和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);
}
}
答案 0 :(得分:1)
以这种方式实施:
这些变量在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
}
答案 1 :(得分:0)
我会用图像路径创建一个字符串数组,然后选择一个随机路径并显示该图像。