一、activity_main.xml
自定義瞭控件,外層是RelativeLayout,裡面是個View,通過設置View的寬度來實現進度條的前進,主要com.jltxgcy.progressbar.ProgressView要和包名一致
二、ProgressView.java
setProgress之所以要延遲20毫秒,是因為隻有這樣才能順利獲取View的高度和寬度。自定義控件可以操作自己的View,通過onFinishInflate,來找到View,然後來操作
package com.jltxgcy.progressbar; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; public class ProgressView extends RelativeLayout { private View mProgress; public ProgressView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { // TODO Auto-generated method stub super.onFinishInflate(); mProgress = findViewById(R.id.progress); } public void setBackgroud() { mProgress.setBackgroundColor(Color.BLUE); } public void setProgress(final int progress) { postDelayed(new Runnable() { @Override public void run() { int width = getWidth(); int height = getHeight(); int curProgress = (int) (progress / 100.0 * width); LayoutParams params = new LayoutParams(curProgress, height); mProgress.setLayoutParams(params); } }, 20); } }
三、MainActivity.java
通過findViewById來操作自定義ProgreeView
package com.jltxgcy.progressbar; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { private ProgressView mProgressView; private int progressRate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mProgressView = (ProgressView) findViewById(R.id.rootview); mProgressView.postDelayed(new updataProgressBar(), 500); } class updataProgressBar implements Runnable{ @Override public void run() { mProgressView.setBackgroud(); mProgressView.setProgress(progressRate); progressRate += 2; mProgressView.postDelayed(new updataProgressBar(), 500); } } }