效果: 效果是这样的,三个实心圆点的背景色来回切换
思路: 1 自定义LinearLayout,添加一个属性动态定义小圆点的个数
2 小圆点的个数是几就创建几个小圆点(ImageView),为小圆点添加背景图片,然后添加到当前布局中
3 将小圆点保存到列表中
4 记录一下当前黑色小圆点的索引,每隔200ms讲下一个小圆点背景设置为黑色(采用handler postDelayed),其他圆 点设置为白色
5 递归调用第四步
代码:
1 创建自定义view
public class MloadingView extends LinearLayout {
private Context context;
private int subviewcount;//小圆点数量
private int countIndex;//当前黑色小圆点索引
private List<ImageView> ivList=new ArrayList<ImageView>();
private Handler handler=new Handler();
private Runnable runnable;
public MloadingView(Context context) {
super(context);
this.context=context;
init();
}
public MloadingView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MloadingView);
subviewcount=typedArray.getInteger(R.styleable.MloadingView_subviewcount,0);
init();
}
public MloadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context=context;
init();
}
2 attr.xml中添加小圆点个数属性subviewcount
<declare-styleable name="MloadingView">
<attr name="subviewcount" format="integer"/>
</declare-styleable>
3 初始化方法中根据subviewcount创建小圆点imageview
public void init(){
ivList.clear();
removeAllViews();
for(int i=0;i<subviewcount;i++){
LayoutParams params = new LayoutParams(30,30);
params.leftMargin=15;
params.gravity= Gravity.CENTER;
ImageView imageView = new ImageView(context);
imageView.setBackgroundResource(R.drawable.yuan_2);
imageView.setLayoutParams(params);
addView(imageView);
ivList.add(imageView);
}
startLoading();
}
4 使用handler.postDelayed动态改变小圆点背景图片
private void startLoading(){
runnable=new Runnable() {
@Override
public void run() {
//如果当前圆点索引大于子view的个数,索引从0开始
if(countIndex>=getChildCount()){
countIndex=0;
}
for(int index=0;index<ivList.size();index++){
//保证当前圆点以及其他圆点的背景色不同
if(index==countIndex){
ivList.get(index).setBackgroundResource(R.drawable.icon_yuan);
}else {
ivList.get(index).setBackgroundResource(R.drawable.icon_yuan_2);
}
}
countIndex++;
startLoading();
}
};
handler.postDelayed(runnable,200);
}
5 页面加载完成之后需要将布局隐藏,清空布局。同时需要注意回收handler