1.佈局文件android
<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:orientation="vertical" android:gravity="center" tools:context="com.example.yuekao005.Main2Activity"> <ProgressBar android:id="@+id/pb" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/but" android:text="點擊" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
2.代碼實現ide
public class Main2Activity extends AppCompatActivity implements View.OnClickListener { private ProgressBar pb; private Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); initView(); } private void initView() { pb = (ProgressBar) findViewById(R.id.pb); but = (Button) findViewById(R.id.but); but.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.but: final ProgressDialog dialog = new ProgressDialog(this); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 設置水平進度條 dialog.setCancelable(true);// 設置是否能夠經過點擊Back鍵取消 dialog.setCanceledOnTouchOutside(false);// 設置在點擊Dialog外是否取消Dialog進度條 dialog.setMax(100); dialog.setMessage("這是一個水平進度條"); dialog.show(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub int i = 0; while (i < 11) { try { Thread.sleep(200); // 更新進度條的進度,能夠在子線程中更新進度條進度 dialog.incrementProgressBy(10); i++; if (i==10) { dialog.dismiss(); //當i==10的時候handler對象發送消息 hand.sendEmptyMessage(1); } } catch (Exception e) { // TODO: handle exception } } // 在進度條走完時刪除Dialog } }).start(); break; } } Handler hand = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what==1) { Intent intent = new Intent(Main2Activity.this, Main2Activity.class); startActivityForResult(intent, 100); } } }; }