首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android ProgressBar XML 大小寫錯誤導致 InflateException

     編輯:程式設計綜合問答

錯誤日志

FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #13: Error inflating class progressBar
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.progressBar"

根因

XML 布局中標籤名區分大小寫,必須與類名完全一致。
正確:<ProgressBar>(P、B 大寫)
錯誤:<progressBar>(全小寫)

修正布局片段

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="進度條" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/progressBarHorizontal"
        android:max="100" />

    <Button android:id="@+id/btnup" ... />
    <Button android:id="@+id/btndown" ... />
</LinearLayout>

Java 代碼補充修正

// 成員變量引用同一個 ProgressBar
private ProgressBar progressBarHorizontal;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressBarHorizontal = findViewById(R.id.progressBarHorizontal);
    // 移除錯誤的 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    // 移除錯誤的 setProgressBarIndeterminateVisibility(true);

    Button btnup = findViewById(R.id.btnup);
    Button btndown = findViewById(R.id.btndown);
    btnup.setOnClickListener(this);
    btndown.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    int step = 5;
    if (view.getId() == R.id.btnup) {
        progressBarHorizontal.incrementProgressBy(step);
    } else if (view.getId() == R.id.btndown) {
        progressBarHorizontal.incrementProgressBy(-step);
    }
    int current = progressBarHorizontal.getProgress();
    Toast.makeText(this, "當前進度:" + current, Toast.LENGTH_SHORT).show();
}

關鍵提示

  • XML 標籤大小寫錯誤是新手高頻坑,IDE 會紅線提示,編譯時直接報 ClassNotFoundException。
  • incrementProgressBy 封裝了邊界檢查,比手動 setProgress 更簡潔。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved