Android 基于帧布局实现一个进度条 FrameLayout+ProgressBar

在FrameLayout中添加一个ProgressBar居中

<ProgressBar
        android:layout_gravity="center"
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

添加一个TextView居中

<TextView
        android:layout_gravity="center"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0%" />

该程序实现了一个跑动的进度条,使用了多线程,参考自:http://www.cnblogs.com/tyjsjl/p/4014285.html

<FrameLayout 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"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用帧布局(FrameLayout)实现一个ProgressBar的动态效果" />

    <ProgressBar
        android:layout_gravity="center"
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_gravity="center"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0%" />

</FrameLayout>
activity_main.xml
package com.example.runprogressbar;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        textView = (TextView) findViewById(R.id.textView1);
        new Thread(new MyThread()).start();
    }
    
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            textView.setText(msg.what + "%");
        }
    };
    
    class MyThread implements Runnable {
        
        private int percentNum = 0;

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = ++percentNum;
                    handler.sendMessage(msg);
                    if (percentNum >= 100)
                        break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
            }
        }
        
    }
}
MainActivity.java

 效果:

原文地址:https://www.cnblogs.com/moonlightpoet/p/5402900.html