Android“只有创建视图层次结构的原始线程才能触及其视图。
我用Android制作了一个简单的音乐播放器。每首歌的视图包含一个SeekBar,实现方式如下:public class Song extends Activity implements OnClickListener,Runnable {
private SeekBar progress;
private MediaPlayer mp;
// ...
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer
progress.setVisibility(SeekBar.VISIBLE);
progress.setProgress(0);
mp = appService.getMP();
appService.playSong(title);
progress.setMax(mp.getDuration());
new Thread(Song.this).start();
}
public void onServiceDisconnected(ComponentName classname) {
appService = null;
}
};
这个很好用。现在我要一个计时器来计算这首歌的进度的秒/分钟。所以我把TextView在布局中,用findViewById()在……里面onCreate(),把这个放进去run()后progress.setProgress(pos):String time = String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(pos),
TimeUnit.MILLISECONDS.toSeconds(pos),
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
pos))
);currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
但最后一行给了我一个例外:android.view.ViewRoot$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。
然而,我在这里所做的与我在这里所做的事情基本上是一样的。SeekBar-在onCreate,然后触摸它run()-但这并没有给我这种抱怨.