Andre Perkins
Andre Perkins

Reputation: 7800

Subclassing Button

I get a ClassCastException when I tried to extend the Button class after trying to make a MusicButton subclass. I am not trying to override the background, only add a few additional methods. I am sure I extended that class correctly so this must be something specific with interacting with Android UI components. Why is this occurring?

Here is the line where I get the ClassCastException:

bMusic = (MusicButton) findViewById(R.id.musicButton);

Here is the MusicButton class:

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();
    }
}
}

Upvotes: 2

Views: 397

Answers (1)

Andre Perkins
Andre Perkins

Reputation: 7800

It turns out that I needed to override a few more constructors from the Button class and make a few changes to the XML.

Here is the code for my Button subclass:

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.....

And the 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" />

Upvotes: 1

Related Questions