一、activity_main.xml
自定义了控件,外层是RelativeLayout,里面是个View,通过设置View的宽度来实现进度条的前进,主要com.jltxgcy.progressbar.ProgressView要和包名一致
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.jltxgcy.progressbar.ProgressView
android:id="@+id/rootview"
android:layout_width="match_parent"
android:layout_height="15dp"
android:background="#d6d6d6" >
<View
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="15dp" />
</com.jltxgcy.progressbar.ProgressView>
</RelativeLayout>
二、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);
}
}
}