Android中ProgressDialog的應用
下面通過實現點擊按鈕來顯示加載框,2秒后自動消失。
1、首先在layout的xml中添加一個按鈕:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="32dp" android:layout_marginTop="14dp" android:background="@drawable/button_style" android:text="@string/btnText" />
2、在后台java代碼中添加View.OnClickListener事件,重寫onClick,代碼如下:
processButton = (Button) findViewById(R.id.button1);
processButton.setOnClickListener(myOnClickLister);
View.OnClickListener myOnClickLister = new View.OnClickListener() { public void onClick(View v) { final ProgressDialog proDialog = android.app.ProgressDialog.show(MainActivity.this, "測試", "2秒后自動消失!"); Thread thread = new Thread() { public void run() { try { sleep(2000); } catch (InterruptedException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } proDialog.dismiss();//萬萬不可少這句,否則會程序會卡死。 } }; thread.start(); } };
3、這樣就利用線程的sleep的方式來實現了。但是要注意的一點是,必須在線程結束時調用對話框對象的dismiss()方法,否則程序將進入死循環當中。卡死在那里。
4、效果出來了,就是這樣的:
本文發表自宋興柱博客員:http://www.cnblogs.com/songxingzhu/