此代码来自一本书。进度对话框似乎显示在非 UI 线程中。
但据我所知,只有在 UI 线程中是可能的。
我想知道为什么可以在非 Ui 线程中显示 ProgressDialog。
public class BackWork3 extends Activity
{
TextView mResult;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.backwork);
mResult = (TextView)findViewById(R.id.result);
}
public void mOnClick(View v)
{
int start = 0, end = 100;
int result;
WaitDlg dlg = new WaitDlg(BackWork3.this, "WaitTest", "Now calculating");
dlg.start();
result = Accumulate(start, end);
mResult.setText("" + result);
WaitDlg.stop(dlg);
}
int Accumulate(int start, int end)
{
int sum = 0;
for (int i = start; i <= end; i++)
{
sum += i;
try { Thread.sleep(20); } catch (InterruptedException e) {;}
}
return sum;
}
}
class WaitDlg extends Thread
{
Context mContext;
String mTitle;
String mMsg;
ProgressDialog mProgress;
Looper mLoop;
WaitDlg(Context context, String title, String msg)
{
mContext = context;
mTitle = title;
mMsg = msg;
setDaemon(true);
}
public void run()
{
Looper.prepare();
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setTitle(mTitle);
mProgress.setMessage(mMsg);
mProgress.setCancelable(false);
mProgress.show();
mLoop = Looper.myLooper();
Looper.loop();
}
static void stop(WaitDlg dlg)
{
dlg.mProgress.dismiss();
try { Thread.sleep(100); } catch (InterruptedException e) {;}
dlg.mLoop.quit();
}
}
//------------------------------------------------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="Start"
/>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="result"
/>
</LinearLayout>