当我单击一个按钮时,我正在尝试进行幻灯片放映,ImageView 将以设定的间隔速度一次一个地显示整数图片 [] 中的所有图片/可绘制对象,我将从屏幕上的单选按钮(3 个选项(中进行选择。
我尝试在没有AsyncTask的情况下一次显示一张一张图像,如下所示,但它只显示最后一张图像,每张图片之间没有时间延迟。
for (Integer p:pics)
{
iv.SetImageResource(p);
SystemClock.sleep(500);
}
以下代码是我目前所拥有的,我需要AsyncTask底部的帮助,如何在设定的间隔时间内逐个实现图像
public class PhotoAlbum extends Activity
{
static final int intSlow = 3000;
static final int intMed = 1000;
static final int intFast = 500;
ImageView iv;
int interval;
Integer pics[] = {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6
};
RadioButton rbSlow;
RadioButton rbMedium;
RadioButton rbFast;
Button mAutoButton;
private int currentImage = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_album);
iv = (ImageView) findViewById(R.id.imageView);
iv.setImageResource(pics[currentImage]);
rbSlow = (RadioButton) findViewById(R.id.radioSlow);
rbMedium = (RadioButton) findViewById(R.id.radioMedium);
rbFast = (RadioButton) findViewById(R.id.radioFast);
mAutoButton = (Button) findViewById(R.id.buttonAuto);
mAutoButton.setOnClickListener(AutoButtonChangeImageListener);
}
private View.OnClickListener AutoButtonChangeImageListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
AutoPicsTask.execute();
}
};
private class AutoPicsTask extends AsyncTask<Integer, Void, Integer>
{
if (rbSlow.isChecked())
{
interval = intSlow;
} else if (rbMedium.isChecked())
{
interval = intMed;
} else
{
interval = intFast;
}
@Override
protected Integer doInBackground(Integer... params)
{
for (Integer p : pics)
{
SystemClock.sleep(interval);
}
return null;
}
protected void onPostExecute(Integer ...value) {
iv.setImageResource(value[0]);
}
}
}
抱歉,我真的是AsyncTask的新手。
这是使用我们目前所学知识的作业。我们还没有学习如何使用"handler",timer,runOnUiThread((,创建一个线程,void run((,postDelayed((,animate,我看到一些帖子建议一次实现一个图像。
提前谢谢。
您正在 onPostExecute 中设置图像资源。您必须在 SystemClock.sleep(interval( 之后或之前执行此操作。在doInBackground((中,你不能改变UI元素,但当然有一个解决方案。
使用 runInUiThread(( 方法。 它需要一个可运行的对象。设置您的图像视图在其中。
for (Integer p : pics){
SystemClock.sleep(interval);
runOnUiThread(new Runnable(){
@Override
public void run() {
iv.setImageResource(p);
}
} );
}
我使用此代码作为计时器
CountDownTimer timer = new CountDownTimer(6000, 1000) { //this will make 5 minute delay
@Override
public void onTick(long millisUntilFinished) {
// write the code of changing pictures
}
@Override
public void onFinish() {
try{
//write the code when finishing
}catch(Exception e){
}
}
}.start();