2014-01-29 24 views
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(); 
    } 
} 
} 
+4

哪裏是你的XML?這就是將指定實際的類在您的視圖實例... –

+0

如果你想找出實際的類的你想投的東西,嘗試'findViewById(R.id.musicButton).getClass() .getName()',它是一個'String',然後做一些事情來顯示這個字符串。 – ajb

+3

與@JonSkeet達成一致 - 我想你只是在佈局XML文件中聲明它只是一個'Button'。您需要將其聲明爲(例如)'' – Squonk

回答

0

事實證明,我需要覆蓋從Button類幾個構造並對XML進行一些更改。

這裏是我的按鈕子類代碼:

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