Android新闻公告切换效果(上下滚动&左右滚动)

- 日理万妓 2023-06-19 09:59 90阅读 0赞

今日,看到淘宝的一个效果,之前做的App中没做过,就实现了一下。使用的是原生的控件TextSwitcher,进行了简单的封装处理。
Android新闻公告切换效果

废话少说,呈上代码。

  1. package com.panghu.view;
  2. import android.content.Context;
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.util.AttributeSet;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.view.animation.Animation;
  9. import android.view.animation.AnimationUtils;
  10. import android.widget.ImageView;
  11. import android.widget.TextSwitcher;
  12. import android.widget.TextView;
  13. import android.widget.ViewSwitcher;
  14. import com.panghu.R;
  15. /** * * 公告新闻切换 * * Wetchat : ljphhj * Github : https://github.com/xiaoyaomeng * Autor : lijiangping */
  16. public class CustomTextSwitcher extends TextSwitcher implements ViewSwitcher.ViewFactory {
  17. private Context mContext;
  18. private String[] mData;
  19. private final long DEFAULT_TIME_SWITCH_INTERVAL = 1000;//1s
  20. private long mTimeInterval = DEFAULT_TIME_SWITCH_INTERVAL;
  21. private int mCurrentIndex = 0;
  22. public CustomTextSwitcher(Context context, AttributeSet attrs) {
  23. super(context, attrs);
  24. this.mContext = context;
  25. setFactory(this);
  26. }
  27. public CustomTextSwitcher setInAnimation(int animationResId){
  28. Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);
  29. setInAnimation(animation);
  30. return this;
  31. }
  32. public CustomTextSwitcher setOutAnimation(int animationResId){
  33. Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);
  34. setOutAnimation(animation);
  35. return this;
  36. }
  37. /** * 通知/公告数据绑定 * @param data * @return */
  38. public CustomTextSwitcher bindData(String[] data){
  39. this.mData = data;
  40. return this;
  41. }
  42. public void startSwitch(long timeInterval){
  43. this.mTimeInterval = timeInterval;
  44. if (mData != null && mData.length != 0) {
  45. mSwitchHandler.sendEmptyMessage(0);
  46. }else{
  47. throw new RuntimeException("data is empty");
  48. }
  49. }
  50. /** * 工厂类中创建TextView供给TextSwitcher使用 * @return */
  51. @Override
  52. public View makeView() {
  53. TextView view = new TextView(this.mContext);
  54. return view;
  55. }
  56. private Handler mSwitchHandler = new Handler(){
  57. @Override
  58. public void dispatchMessage(Message msg) {
  59. super.dispatchMessage(msg);
  60. int index = mCurrentIndex % mData.length;
  61. mCurrentIndex++;
  62. setText(mData[index]);
  63. sendEmptyMessageDelayed(0, mTimeInterval);
  64. }
  65. };
  66. }

Demo下载地址: https://github.com/xiaoyaomeng/CustomTextSwitcher

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读