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); } } }; }