ViewFlipper自带轮播功能,可以设置间隔时间,item进去和退出的动画;
ViewFlipper添加需要滚动的view。
demo的思路:自定义ViewFlipper,初始化中设置它的滚动间隔时间,进去和结束的动画,然后在数据源的set方法中添加textview和imageview
public class MViewFlipper extends ViewFlipper {
OnCheckedListener onCheckedListener;
public void setOnCheckedListener(OnCheckedListener onCheckedListener) {
this.onCheckedListener = onCheckedListener;
}
Context mContext;
List<String> allData;
public interface OnCheckedListener {
void onClick(int position);
}
public MViewFlipper(Context context) {
super(context);
}
public MViewFlipper(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
mContext = context;
//间隔时间
setFlipInterval(3000);
//设置间隔
setPadding(5, 5, 5, 5);
//设置进入和出去的动画
//出去的动画
AnimationSet animationSetOut = new AnimationSet(true);
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
// alphaAnimation.setStartOffset(500);
TranslateAnimation translateAnimation = new TranslateAnimation(getX(), getX(), 0, -100);
animationSetOut.addAnimation(translateAnimation);
animationSetOut.addAnimation(alphaAnimation);
animationSetOut.setDuration(1000);
setOutAnimation(animationSetOut);
//进来的动画
AnimationSet animationSetIn = new AnimationSet(true);
AlphaAnimation alphaAnimation1 = new AlphaAnimation(0, 1);
// alphaAnimation1.setStartOffset(500);设置延迟执行动画
TranslateAnimation translateAnimatio1n = new TranslateAnimation(getX(), getX(), 100, 0);
animationSetIn.addAnimation(translateAnimatio1n);
animationSetIn.addAnimation(alphaAnimation1);
animationSetIn.setDuration(1000);
setInAnimation(animationSetIn);
}
public void setAllData(List<String> allData) {
this.removeAllViews();
this.allData = allData;
//把数据添加到viewflipper里面
for (int i = 0; i < allData.size(); i++) {
TextView textView = new TextView(mContext);
final int finalI = i;
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onCheckedListener.onClick(finalI);
}
});
textView.setSingleLine();
textView.setTextSize(17.0f);
textView.setText(allData.get(i));
textView.setTextColor(Color.parseColor("#FF4081"));
textView.setGravity(Gravity.CENTER);
addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
ImageView imageView = new ImageView(mContext);
imageView.setBackgroundDrawable(getResources().getDrawable(R.mipmap.ic_launcher));
addView(imageView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
}
}