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

당신의 XML이있어 여기에

은 내 버튼 하위 클래스에 대한 코드? 그것은 당신의 뷰에서 인스턴스화 할 실제 클래스를 지정하는 것입니다 ... –

+0

캐스팅하려는 실제 클래스를 찾으려면'findViewById (R.id.musicButton) .getClass()를 시도하십시오. .getName()', 이는'String'이며,이 문자열을 표시하기 위해 뭔가를하십시오. – ajb

+3

@JonSkeet과 동의 - 레이아웃 XML 파일에서 'Button'으로 선언하고있는 것 같습니다. 예를 들어' '이라고 선언해야합니다. – Squonk

답변

0

내가 Button 클래스에서 몇 생성자를 오버라이드 (override) 할 필요가 있다고 밝혀 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" />