จำลองการทำงานบางอย่าง 3 วินาทีแล้วปิด
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?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:layout_width="match_parent" android:layout_height="match_parent" android:background="#EEE" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Do some stuff" /> <ProgressBar android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:visibility="gone" /> </LinearLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.phaisarns.acrosuredemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ProgressBar progressBar = findViewById(R.id.progressBar); Button button = findViewById(R.id.button); // when button is clicked, start the task button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //update ui on UI thread runOnUiThread(new Runnable() { @Override public void run() { progressBar.setVisibility(View.GONE); } }); } }).start(); } }); } } |
บรรทัดที่ 23 : แสดง progressBar
บรรทัดที่ 35 : เมื่อ Thread ทำงานเสร็จ จะมาทำฟังก์ชันนี้เพื่อทำการอัพเดท UI
บรรทัดที่ 38 : ซ่อน progressBar
Link