在 Android 中自定義進度條?
這個例子展示瞭如何在 android 中建立一個進度條
第 1 步 − 在 Android Studio 中建立新專案,轉到 File ⇒ New Project 並填寫所有必需資訊以建立新專案。
第 2 步 − 在 res/layout/activity_main.xml 中新增以下程式碼。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ProgressBar android:layout_width="150dp" android:layout_height="150dp" style="?android:progressBarStyleLarge" android:progress="50" android:id="@+id/progressBar" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:progressDrawable="@drawable/circle"/> </android.support.constraint.ConstraintLayout>
第 3 步 − 建立一個 drawable 資原始檔,將其命名為 circle.xml 並新增以下程式碼 −
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="ring" android:innerRadiusRatio="2.5" android:thickness="4dp" android:useLevel="true"> <solid android:color="@color/colorAccent"/>
第 4 步 − 在 src/MainActivity.java 中新增以下程式碼
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity { ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = findViewById(R.id.progressBar); progressBar.setMax(100); progressBar.setProgress(20); } }
第 5 步 − 在 androidManifest.xml 中新增以下程式碼
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
讓我們嘗試執行你的應用程式。我認為你已將你的實際 Android 手機裝置與你的電腦連線在一起。要從 android studio 執行該應用程式,請開啟你的一個專案的活動檔案並單擊工具欄中的 Run 圖示。選擇你的移動裝置作為選項,然後檢視將顯示你的預設螢幕的移動裝置 −
單擊此處下載專案程式碼。
廣告