我在Android中創建了一個進度條,但它一點也不工作。我究竟做錯了什麼?我剛開始學習android。以下是我的代碼。Android進度條無法正常工作
MainActivity.java-
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
Activity_main.xml-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="@+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="@+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
看看這個圖片如下─ - https://i.stack.imgur.com/2TBIb.png
注意 - 此圖像中輸入時間爲一個EditText提示而不是TextView。
它出現,但不工作。
我有這麼far.- https://i.stack.imgur.com/UujpB.png
但還是進度條仍然連續旋轉完成這些變化。
定義 「完全沒有工作」。根本不顯示?沒有更新?還有其他的東西嗎? –
@GabeSechan我已經更新了這個問題。請檢查它。 – Knattic
我想,它是因爲你正在MainThread上調用睡眠。嘗試將睡眠呼叫轉移到外線程。 –