Android 뉴스 광고 바 스크롤 효과

16215 단어 Android굴러가다
프로젝트 에 서 는 게시판 과 같은 컨트롤 을 사용 해 야 합 니 다.사용 할 수 있 는 것 은 기본적으로 여러 줄 의 디 스 플레이 를 지원 하지 않 기 때문에 스스로 손 을 쓸 수 밖 에 없습니다.그럴듯 한 컨트롤 을 사용자 정의 하지 않 았 기 때문에 참고 할 수 있 습 니 다Android 게시판 데모여러 줄 이 위로 굴 러 가 는 컨트롤 을 실 현 했 습 니 다.원래 컨트롤 을 바탕 으로 다음 과 같은 기능 을 추가 합 니 다.
 •데이터 페이지 표시 전송
 •Left Drawable 추가
 •손가락 터치 사건 처리
 •3D 애니메이션 스크롤 백 효과 추가
효과 도

소스 코드

package com.android.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sd2w.market.client.R;

import java.util.ArrayList;
import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 *      
 *
 * @author    
 * @version 1.0
 * @date 2016-08-17
 */

public class RollingView extends FrameLayout implements OnClickListener {

 //         
 private static final int ANIMATION_DURATION = 1000;

 //         
 private long mDuration = 3000;
 //     
 private int mTextColor = 0xff000000;
 //        
 private int mClickColor = 0xff0099ff;
 //     
 private float mTextSize = 14;
 //    
 private int mTextPadding = 10;
 //   
 private Paint mPaint;
 //        
 private int mPageSize = 3;
 //       
 private int mUpLimited = mPageSize;
 //       
 private int mCurrentPage = 0;
 //     
 private int mPageCount;
 //    
 private int mLeftDrawable;
 //       
 private List<LinearLayout> mRollingPages;
 //     
 private AnimationSet mEnterAnimSet;
 private AnimationSet mExitAnimSet;
 private RollingRunnable mRunnable;
 private Handler mHandler;
 private onItemClickListener mClickListener;
 //     
 private LayoutParams mFrameParams;
 private LinearLayout.LayoutParams mLinearParams;
 //mEnterDownAnim,mOutUp             
 private Rotate3dAnimation mEnterDownAnim;
 private Rotate3dAnimation mExitUpAnim;

 //mEnterUpAnim,mOutDown             
 private Rotate3dAnimation mEnterUpAnim;
 private Rotate3dAnimation mExitDownAnim;

 public RollingView(Context context) {
  this(context, null);
 }

 public RollingView(Context context, AttributeSet attrs) {
  super(context, attrs);
  //  xml     
  TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.RollingView);
  mTextSize = array.getDimension(R.styleable.RollingView_textSize, mTextSize);
  mTextColor = array.getColor(R.styleable.RollingView_textColor, mTextColor);
  array.recycle();
  //           
  createEnterAnimation();
  createExitAnimation();
  //      
  mPaint = new TextPaint();
  //    Handler  
  mHandler = new Handler(Looper.getMainLooper());

  mEnterDownAnim = createAnim(-90, 0, true, true);
  mExitUpAnim = createAnim(0, 90, false, true);
  mEnterUpAnim = createAnim(90, 0, true, false);
  mExitDownAnim = createAnim(0, -90, false, false);
 }

 private Rotate3dAnimation createAnim(float start, float end, boolean turnIn, boolean turnUp) {
  final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
  rotation.setDuration(300);
  rotation.setFillAfter(false);
  rotation.setInterpolator(new AccelerateInterpolator());
  return rotation;
 }

 /**
  *       
  *
  * @param pageSize
  */
 public void setPageSize(int pageSize) {
  this.mPageSize = this.mUpLimited = pageSize;
 }

 /**
  *       
  *
  * @param millionSeconds
  */
 public void setDelayedDuration(long millionSeconds) {
  this.mDuration = millionSeconds;
 }

 /**
  *       
  *
  * @param animation
  */
 public void setEnterAnimation(AnimationSet animation) {
  mEnterAnimSet = animation;
 }

 /**
  *       
  *
  * @param animation
  */
 public void setExitAnimation(AnimationSet animation) {
  mExitAnimSet = animation;
 }

 /**
  *     
  *
  * @param padding
  */
 public void setTextPadding(int padding) {
  this.mTextPadding = padding;
 }

 /**
  *          
  *
  * @param color
  */
 public void setClickColor(int color) {
  this.mClickColor = color;
 }

 /**
  *      
  *
  * @param drawable
  */
 public void setLeftDrawable(int drawable) {
  this.mLeftDrawable = drawable;
 }

 /**
  *       
  *
  * @param clickListener
  */
 public void setOnItemClickListener(onItemClickListener clickListener) {
  if (null == clickListener) return;
  this.mClickListener = clickListener;
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  //         ,      300px
  int exceptWidth = 300;
  int exceptHeight = 0;
  //     ,        textSize   ,            。
  if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {
   if (mTextSize > 0) {
    mPaint.setTextSize(mTextSize);
    Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
    exceptHeight = (int) (fontMetrics.bottom - fontMetrics.top);
   }
  }
  int width = resolveSize(exceptWidth, widthMeasureSpec);
  int height = resolveSize(exceptHeight, heightMeasureSpec);
  setMeasuredDimension(width, height);
 }

 public void setRollingText(List<String> array) {
  if (null == array || array.isEmpty()) return;
  this.removeAllViews();
  if (mRollingPages == null) {
   mRollingPages = new ArrayList<>();
  }
  mRollingPages.clear();
  //     
  int quotient = array.size() / mPageSize;
  //     
  int remainder = array.size() % mPageSize;
  //          
  mPageCount = remainder == 0 ? quotient : quotient + 1;
  for (int i = 0; i < mPageCount; i++) {
   //       
   LinearLayout container = createContainer();
   if (i == mPageCount - 1) {
    mUpLimited = remainder == 0 ? mPageSize : remainder;
   }
   for (int n = 0; n < mUpLimited; n++) {
    TextView textView = createTextView(array.get(mPageSize * i + n));
    container.addView(textView);
   }
   //       
   mRollingPages.add(container);
   this.addView(container);
  }
  //         
  mCurrentPage = 0;
  mRollingPages.get(mCurrentPage).setVisibility(VISIBLE);
  this.setVisibility(mRollingPages.get(mCurrentPage));
 }

 /**
  *      
  *
  * @return
  */
 private LinearLayout createContainer() {
  if (mFrameParams == null) {
   mFrameParams = new LayoutParams(MATCH_PARENT, WRAP_CONTENT);
   mFrameParams.gravity = Gravity.CENTER_VERTICAL;
  }
  LinearLayout container = new LinearLayout(getContext());
  container.setLayoutParams(mFrameParams);
  container.setOrientation(LinearLayout.VERTICAL);
  return container;
 }

 private void setVisibility(LinearLayout container) {
  int count = container.getChildCount();
  for (int i = 0; i < count; i++) {
   container.getChildAt(i).setVisibility(VISIBLE);
  }
 }

 /**
  *        
  *
  * @param text
  * @return
  */
 private TextView createTextView(String text) {
  if (mLinearParams == null) {
   mLinearParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
   mLinearParams.gravity = Gravity.CENTER_VERTICAL;
  }
  TextView textView = new TextView(getContext());
  textView.setLayoutParams(mLinearParams);
  textView.setSingleLine();
  textView.setPadding(mTextPadding, mTextPadding, mTextPadding, mTextPadding);
  textView.setEllipsize(TextUtils.TruncateAt.END);
  textView.setTextColor(mTextColor);
  textView.setVisibility(INVISIBLE);
  textView.setText(text);
  if (mLeftDrawable > 0) {
   Drawable drawable = getContext().getResources().getDrawable(mLeftDrawable);
   // Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), mLeftDrawable);
   // Drawable drawable = new BitmapDrawable(getContext().getResources(), bitmap);
   drawable.setBounds(0, 0, 10, 10);
   textView.setCompoundDrawablePadding(10);
   textView.setCompoundDrawables(drawable, null, null, null);
  }
  textView.setOnClickListener(this);
  //       
  if (mTextSize > 0) {
   textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
  }
  return textView;
 }

 private void createEnterAnimation() {
  mEnterAnimSet = new AnimationSet(false);
  TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, 0, TranslateAnimation.RELATIVE_TO_PARENT, 1f, TranslateAnimation.RELATIVE_TO_SELF, 0f);
  AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
  mEnterAnimSet.addAnimation(translateAnimation);
  mEnterAnimSet.addAnimation(alphaAnimation);
  mEnterAnimSet.setDuration(ANIMATION_DURATION);
 }

 private void createExitAnimation() {
  mExitAnimSet = new AnimationSet(false);
  TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, 0, TranslateAnimation.RELATIVE_TO_SELF, 0f, TranslateAnimation.RELATIVE_TO_PARENT, -1f);
  AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
  mExitAnimSet.addAnimation(translateAnimation);
  mExitAnimSet.addAnimation(alphaAnimation);
  mExitAnimSet.setDuration(ANIMATION_DURATION);
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  int action = event.getAction();
  switch (action) {
   case MotionEvent.ACTION_DOWN:
    pause();
    break;
   case MotionEvent.ACTION_MOVE:
   case MotionEvent.ACTION_UP:
   case MotionEvent.ACTION_CANCEL:
    resume();
    break;
  }
  return true;
 }

 public void resume() {
  //           
  if (mPageCount < 1) return;
  if (mRunnable == null) {
   mRunnable = new RollingRunnable();
  } else {
   mHandler.removeCallbacks(mRunnable);
  }
  mHandler.postDelayed(mRunnable, mDuration);
 }

 public void pause() {
  if (mRunnable != null) {
   mHandler.removeCallbacks(mRunnable);
  }
 }

 @Override
 public void onClick(View v) {
  if (null == mClickListener) return;
  TextView textView = (TextView) v;
  mClickListener.onItemClick(textView);
  textView.setTextColor(mClickColor);
 }

 /**
  *      ,       
  */
 public class RollingRunnable implements Runnable {

  @Override
  public void run() {
   //      
   LinearLayout currentView = mRollingPages.get(mCurrentPage);
   currentView.setVisibility(INVISIBLE);
   if (mExitAnimSet != null) {
    currentView.startAnimation(mExitAnimSet);// mExitUpAnim);
   }
   mCurrentPage++;
   if (mCurrentPage >= mPageCount) {
    mCurrentPage = 0;
   }
   //      
   LinearLayout nextView = mRollingPages.get(mCurrentPage);
   nextView.setVisibility(VISIBLE);
   setVisibility(nextView);
   if (mEnterAnimSet != null) {
    nextView.startAnimation(mEnterAnimSet);// mEnterDownAnim);
   }
   mHandler.postDelayed(this, mDuration);
  }
 }

 public class Rotate3dAnimation extends Animation {
  private final float mFromDegrees;
  private final float mToDegrees;
  private final boolean mTurnIn;
  private final boolean mTurnUp;
  private float mCenterX;
  private float mCenterY;
  private Camera mCamera;

  public Rotate3dAnimation(float fromDegrees, float toDegrees, boolean turnIn, boolean turnUp) {
   mFromDegrees = fromDegrees;
   mToDegrees = toDegrees;
   mTurnIn = turnIn;
   mTurnUp = turnUp;
  }

  @Override
  public void initialize(int width, int height, int parentWidth, int parentHeight) {
   super.initialize(width, height, parentWidth, parentHeight);
   mCamera = new Camera();
   mCenterY = getHeight() / 2;
   mCenterX = getWidth() / 2;
  }

  @Override
  protected void applyTransformation(float interpolatedTime, Transformation t) {
   final float fromDegrees = mFromDegrees;
   float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

   final float centerX = mCenterX;
   final float centerY = mCenterY;
   final Camera camera = mCamera;
   final int derection = mTurnUp ? 1 : -1;

   final Matrix matrix = t.getMatrix();

   camera.save();
   if (mTurnIn) {
    camera.translate(0.0f, derection * mCenterY * (interpolatedTime - 1.0f), 0.0f);
   } else {
    camera.translate(0.0f, derection * mCenterY * (interpolatedTime), 0.0f);
   }
   camera.rotateX(degrees);
   camera.getMatrix(matrix);
   camera.restore();

   matrix.preTranslate(-centerX, -centerY);
   matrix.postTranslate(centerX, centerY);
  }
 }

 public interface onItemClickListener {
  void onItemClick(TextView v);
 }
}
쓰다

//        
List<String> haowaiArray = new ArrayList<>();
haowaiArray.add("[    ]            ");
haowaiArray.add("[    ]  100    ");
haowaiArray.add("[   ]       8 /kg");
haowaiArray.add("[    ]           ");
haowaiArray.add("[    ]   9.9   ");
haowaiArray.add("[    ]      ");
haowaiArray.add("[   ]   VR   13");
haowaiArray.add("[    ]       -    ");
//     
mRollingView.setPageSize(4);
mRollingView.setClickColor(0xff888888);
mRollingView.setLeftDrawable(R.drawable.drawable_red_dot);
mRollingView.setRollingText(haowaiArray);
mRollingView.setOnItemClickListener(this);

...

@Override
public void onItemClick(TextView v) {
 // handle item click event
}

@Override
public void onResume() {
 super.onResume();
 mRollingView.resume();
}
@Override
public void onPause() {
 super.onPause();
 mRollingView.pause();
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기