1
我得到一個ClassCastException
當我試圖努力使MusicButton
子後延長Button
類。我不想重寫背景,只添加一些額外的方法。我相信我正確地擴展了這個類,所以這必須是與Android UI組件交互的特定事物。爲什麼會發生?子類按鈕
這裏是線在那裏我得到了ClassCastException
:
bMusic = (MusicButton) findViewById(R.id.musicButton);
這裏是MusicButton類:
public class MusicButton extends Button implements MusicObserver {
MusicService musicService;
public MusicButton(Context context) {
super(context);
}
/**
* Because we use findViewById to obtain view elements, the service instance
* variable has to be initialized here instead of constructor.
*
* @param service
*/
public void setMusicService(MusicService musicService) {
this.musicService = musicService;
update();
}
public void update() {
/** setMusicService should have been called */
Assert.assertNotNull(musicService);
if (musicService.isMusicPlaying()) {
this.setText("Stop Music");
} else {
this.setText("Play Music");
}
}
/**
* This function does not update the text of the button even though it knows
* the status of the music player becuase I want all music observers to be
* updated consistently, regardless if they are the ones forcing the
* notification to occurr
*/
public void buttonPressed() {
Assert.assertNotNull(musicService);
if (musicService.isMusicPlaying()) {
musicService.pauseMusic();
} else {
musicService.playMusic();
}
}
}
哪裏是你的XML?這就是將指定實際的類在您的視圖實例... –
如果你想找出實際的類的你想投的東西,嘗試'findViewById(R.id.musicButton).getClass() .getName()',它是一個'String',然後做一些事情來顯示這個字符串。 – ajb
與@JonSkeet達成一致 - 我想你只是在佈局XML文件中聲明它只是一個'Button'。您需要將其聲明爲(例如)'' –
Squonk