1
서브 클래스 MusicButton
을 작성한 후에 Button
클래스를 확장하려고 시도했을 때 ClassCastException
이 표시됩니다. 배경을 덮어 쓰려고하는 것이 아니라 몇 가지 추가 메소드 만 추가하려고합니다. 이 클래스를 올바르게 확장 했으므로 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