歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android學習筆記之ProgressDialog的使用

Android學習筆記之ProgressDialog的使用

日期:2017/3/1 9:55:59   编辑:Linux編程

在很多PC軟件或手機軟件中,我們都會看見 “加載中...” 類似的對話框,當然,在Android應用程序中也是如此。如果我們想在android應用程序中使用這樣的效果,那麼就需要用到ProgressDialog。首先,我們來看一下ProgressDialog這個類。

ProgressDialog類繼承自AlertDialog類,同樣存放在android.app包中。ProgressDialog有兩種形式,一種是圓圈旋轉形式,一種是水平進度條形式,選擇哪種形式可以通過以下兩個屬性值來設定:

static int STYLE_HORIZONTAL
Creates a ProgressDialog with a horizontal progress bar. static int STYLE_SPINNER
Creates a ProgressDialog with a ciruclar, spinning progress bar.

注意,當設置為水平進度條形式時,進度的取值范圍為0—10000。

ProgressDialog的構造方法有以下兩種:

ProgressDialog(Context context) ProgressDialog(Context context, int theme)

除了構造方法外,ProgressDialog還提供的如下的靜態方法返回ProgressDialog對象:

static ProgressDialog show(Context context,CharSequence title, CharSequence message) static ProgressDialog show(Context context,CharSequence title, CharSequence message, boolean indeterminate) static ProgressDialog show(Context context,CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) static ProgressDialog show(Context context,CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable, DialogInterface.OnCancelListener cancelListener)

需要留意的是第一個參數必須是目前運行的Activity的Context。

android的ProgressDialog必須要在後台程序運行完畢前,以dismiss()方法來關閉取得焦點的對話框,否則程序就會陷入無法終止的無窮循環中。在線程中,不得有任何更改Context或parent View的任何狀態,文字輸出等時間,因為線程裡的Context與View並不屬於parent,兩者之間也沒有關聯。

我們以下面一個簡單的程序來學習ProgressDialog的應用:

public class MainActivity extends Activity
{
private Button button=null;
public ProgressDialog dialog=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.button=(Button)super.findViewById(R.id.button);
this.button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final CharSequence strDialogTitle=MainActivity.this.getString(R.string.str_dialog_title);
final CharSequence strDialogBody=MainActivity.this.getString(R.string.str_dialog_body);
//顯示Progress對話框
dialog=ProgressDialog.show(MainActivity.this,strDialogTitle,strDialogBody,true);

new Thread()
{
@Override
public void run()
{
try
{
//表示後台運行的代碼段,以暫停3秒代替
sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
//卸載dialog對象
dialog.dismiss();
}
}

}.start();
}
});
}

}

該程序布局管理器僅需一個Button組件(id為button)即可,此處不再給出。

注意,為了代碼更加符合規范,本程序在strings.xml中定義了如下字符串資源:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">demo2</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="execute">執行</string>
<string name="str_dialog_title">請稍等片刻</string>
<string name="str_dialog_body">正在執行...</string>

</resources>

程序運行效果截圖:

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved