在尝试创建ClassCastException
子类后尝试扩展Button
类时,我得到MusicButton
。我不是要覆盖背景,只添加一些额外的方法。我确信我正确地扩展了该类,因此这必须是与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();
}
}
}
答案 0 :(得分:0)
事实证明,我需要从Button类中覆盖一些构造函数,并对XML进行一些更改。
以下是我的Button子类的代码:
public MusicButton(Context context) {
super(context);
}
public MusicButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MusicButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
//rest of code irrelevant.....
和XML:
<view
android:id="@+id/musicButton"
style="@style/CustomTheme.View.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
class="com.GameOfThrones.Trivia.ui.music.MusicButton"
android:text="Start Music" />