java.lang.ClassCastException: android.widget.SeekBar cannot be cast to org.holoeverywhere.widget.SeekBar
at ...findViewById(R.id.sectionTimeElapsedSeekBar)
佈局 XML 使用標準 <SeekBar>,但 Java 代碼強制轉型為 org.holoeverywhere.widget.SeekBar,導致運行時崩潰。
**XML 標籤名決定實例化類型**。
<SeekBar> → 系統解析為 android.widget.SeekBar<org.holoeverywhere.widget.SeekBar> → 解析為 HoloEverywhere 庫的 SeekBar兩者**無繼承關係**(或非同一類),無法強制轉型。
<org.holoeverywhere.widget.SeekBar
android:id="@+id/sectionTimeElapsedSeekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/startOrPauseTimerButton"
android:layout_alignParentLeft="true"
android:layout_marginBottom="16dp"
android:max="2100" />
import org.holoeverywhere.widget.SeekBar;
// ...
private SeekBar sectionTimeElapsedSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// 現在 findViewById 返回的就是 org.holoeverywhere.widget.SeekBar
sectionTimeElapsedSeekBar = findViewById(R.id.sectionTimeElapsedSeekBar);
// 或顯式轉型(可省略)
// sectionTimeElapsedSeekBar = (SeekBar) findViewById(R.id.sectionTimeElapsedSeekBar);
}
setContentView 觸發 LayoutInflater.inflate()<SeekBar> → 默認包 android.widget.<com.pkg.CustomView> → 直接加載該類findViewById 返回實際實例化的對象類型因此,**XML 聲明的類型必須與 Java 變量類型一致**。
若 HoloEverywhere SeekBar 有自定義屬性(如 holo:style),需在根佈局宣告命名空間:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:holo="https://schemas.android.com/apk/res-auto"
...>
<org.holoeverywhere.widget.SeekBar
...
holo:style="@style/Holo.SeekBar" />
</LinearLayout>
| 錯誤現象 | 原因 | 修正 |
|---|---|---|
| ClassCastException: TextView → CustomTextView | XML 用 <TextView> | XML 改 <com.pkg.CustomTextView> |
| ClassCastException: Fragment → SupportFragment | XML 用 <fragment android:name="..."/> 類不匹配 | 檢查 android:name 完整類名 |
| InflateException: Binary XML file line | 自定義 View 構造函數缺失 (Context, AttributeSet) | 補全兩參構造函數 |
**XML 標籤全限定名 = 實例化類型**。使用第三方庫的自定義 View 時,務必在佈局文件中寫完整包路徑 <org.holoeverywhere.widget.SeekBar>,Java 端直接用該類型接收,杜絕 ClassCastException。這是 Android View 通用原理,適用於所有自定義/第三方 View。