我自定义的Loading 效果如下图:
中间不分就是我自己定义的Loading,这个原理是用自定义的ImageView 用子线程不停的设置ImageView的背景图片,通过设置setVisibility的值来启动和停止、隐藏和显示图片,实现朱振动环。代码如下:
public class Loading extends ImageView {
private Handler handler;
private int count = 3;
private int[] ids = { R.drawable.loading_img01, R.drawable.loading_img02,
R.drawable.loading_img03 };
private boolean isStart = false;
private Thread thread;
public Loading(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
setData();
}
public Loading(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setData();
}
public Loading(Context context) {
super(context);
// TODO Auto-generated constructor stub
setData();
}
public void setData() {
handler = new Handler() {
public void handleMessage(Message msg) {
setBackgroundResource(ids[msg.what]);
}
};
}
public void play() {
thread=new Thread() {
@Override
public void run() {
while (isStart) {
for (int i = 0; i < count; i++) {
final Message message = new Message();
message.what = i;
handler.sendMessage(message);
try {
this.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
}
@Override
public void setVisibility(int visibility) {
// TODO Auto-generated method stub
switch (visibility) {
case View.INVISIBLE:
isStart=false;
break;
case View.VISIBLE:
isStart=true;
play();
thread.start();
break;
case View.GONE:
isStart=false;
break;
}
super.setVisibility(visibility);
}
xml布局中的加入这个Loading
<com.yidaoxing.aaf.view.Loading
android:id="@+id/progressBar_dashen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />