以下代码用于我的应用程序中的启动画面。我需要做的是当 Activity 加载图像时应显示为默认图像,然后几秒钟后图像应更改为同一 Activity 中的另一个图像。我有另一幅图像,如第一幅图像,颜色不同。我想在几秒钟后更改该图像的屏幕。
我已经在我的代码中这样做了。
package com.ruchira.busguru;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class SplashScreen extends Activity {
ImageView imgBus;
MediaPlayer introSound, bellSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
imgBus = (ImageView) findViewById(R.id.imgBus);
imgBus.setImageResource(R.drawable.blackbus);
introSound = MediaPlayer.create(SplashScreen.this, R.raw.enginestart);
introSound.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
imgBus.setImageResource(R.drawable.bluekbus);
}
}
};
timer.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.splash_screen, menu);
return true;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
introSound.stop();
finish();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
introSound.stop();
finish();
}
}
但问题是程序在线程中执行时停止说...
“android.view.ViewRoot$CalledFromWrongThreadException:只有创建 View 层次结构的原始线程才能触及它的 View 。”
我怎样才能实现这个目标?有没有人请帮我解决这个问题。我是 android 开发的新手..
谢谢。
最佳答案
您应该使用 ImageView 的处理程序和一个 Runnable。处理程序是特定于 Android 的调度程序,它们可以在 UI 线程上运行。试试这个:
ImageView imgBus;
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
@Override
public void run() {
imgBus.setImageResource(R.drawable.bluekbus);
}
};
在 onCreate()
调用中:
imgBus = (ImageView) findViewById(R.id.imgBus);
imgBus.setImageResource(R.drawable.blackbus);
imgBus.postDelayed(swapImage, 3000); // Add me!
了解启动画面是不受欢迎的,因为您应该专注于尽快启动应用程序(同时在后台加载较慢的元素)。然而,有时轻微的延迟是不可避免的。
关于Android - 几秒钟后在运行时更改 ImageView 源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13374053/