最近做项目的时候产品提出需要做出类似某金所首页头部消息的样式效果。
与Android系统自带控件不同的是消息不是上下滚动而是伸缩展示,根据文案动态改变View宽度。
经过调研目前系统中有类似的控件 ViewFlipper
,TextSwticher
,ViewSwticher
,ImageViewSwticher
等。
这些控件都可以实现类似某宝,某东首页消息滚动的效果,但是无法实现产品提出的效果。
最后通过自定义控件并继承TextSwticher
,测量出文本长度来动态改变显示父View的宽。
先看下实现的效果:
调研
经查阅资料发现ViewFliper类似ViewPager适合处理复杂布局的消息滚动,不太好获取Child宽度及调整父View宽度;
ImageViewSwticher适合处理简单图片的滚动;
TextSwticher适合处理简单文本的滚动,方便获取文本宽度及调整父View宽度;
TextSwticher通过ViewFactory构造出Child,showNext()展示下一个,
setInAnimation()设置进入动画,setOutAnimation设置退出动画;
根据要求我们需要重写ViewFactory,自定义showNext,自定义动画。
setViewFactory
自定义ViewFactory,根据需求实现makeView方法。
1 2 3 4 5 6 7 8 9 10 @Override public View makeView () { TextView childTextView = new TextView(getContext()); childTextView.setSingleLine(true ); childTextView.setTextSize(16 ); childTextView.setFocusable(true ); childTextView.setFocusableInTouchMode(true ); childTextView.setTextColor(getContext().getResources().getColor(android.R.color.black)); return childTextView; }
showNextText
自定义方法实现兼容展示下一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 private void showNextText () { setNextChild(); } private void setNextChild () { if (mCurrentIndex > mContentList.size() - 1 ) { mCurrentIndex = 0 ; } TextView mNextView = (TextView) getNextView(); String mContent = mContentList.get(mCurrentIndex++); mNextView.setText(HtmlCompat.fromHtml(mContent, HtmlCompat.FROM_HTML_MODE_LEGACY)); int hash = mContent.hashCode(); Float measureWidth = mViewSizeCache.get(hash); if (null == measureWidth) { measureWidth = mNextView.getPaint().measureText(mContent) + mNextView.getPaddingRight() + mNextView.getPaddingLeft(); mViewSizeCache.put(hash, measureWidth); } MarginLayoutParams param = (MarginLayoutParams) mNextView.getLayoutParams(); if (MAX_WIDTH < measureWidth.intValue()) { param.width = MAX_WIDTH - getPaddingLeft() - getPaddingRight(); } else { param.width = measureWidth.intValue(); } mNextView.setLayoutParams(param); showNext(); setCurrentViewMarginLeft(0 ); float originalTextWidth = getCurrentViewWidth(); setCurrentWidth(originalTextWidth); }
动画
去掉默认动画,通过ValueAnimator来实现进出动画。
设置AnimatorUpdateListener监听器,根据进度动态父View宽度
1 2 3 4 5 6 7 8 9 private final AnimatorUpdateListener mUpdateListener = new AnimatorUpdateListener() { @Override public void onAnimationUpdate (ValueAnimator animation) { float mCurrentWidth = getCurrentViewWidth(); float factor = (float ) animation.getAnimatedValue(); mCurrentWidth = Math.round(mCurrentWidth * factor); setCurrentWidth(mCurrentWidth); } };
完整源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 package com.dxmat.test.dxmtest;import android.animation.Animator;import android.animation.Animator.AnimatorListener;import android.animation.ObjectAnimator;import android.animation.ValueAnimator;import android.animation.ValueAnimator.AnimatorUpdateListener;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.text.TextUtils.TruncateAt;import android.util.ArrayMap;import android.util.AttributeSet;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import android.view.animation.LinearInterpolator;import android.widget.TextSwitcher;import android.widget.TextView;import android.widget.ViewSwitcher;import androidx.core.text.HtmlCompat;import java.util.ArrayList;import java.util.List;public class AutoSizeTextSwither extends TextSwitcher implements ViewSwitcher .ViewFactory { private static final int DEFAULT_DURATION = 500 ; private static int MAX_WIDTH = 800 ; private boolean mAutoStart = false ; private boolean mStarted = false ; private boolean mVisible = false ; private boolean mRunning = false ; private long mIntervalIn = DEFAULT_DURATION; private long mIntervalOut = DEFAULT_DURATION; private List<String> mContentList = new ArrayList<>(3 ); private boolean mUserPresent = true ; private volatile int mCurrentIndex; private final ValueAnimator mAnimationIn = ObjectAnimator.ofFloat(0 , 1 ); private final ValueAnimator mAnimationOut = ObjectAnimator.ofFloat(1 , 0 ); private final ValueAnimator marqueeAnimation = ObjectAnimator.ofFloat(); private final ArrayMap<Integer, Float> mViewSizeCache = new ArrayMap<>(3 ); private float marqueeOffset; private long mInterval = DEFAULT_DURATION; private TruncateAt truncateAt = null ; private OnItemClickListener onItemClickListener; public interface OnItemClickListener { void onItemClick (View view, String text, int position) ; } private final AnimatorListener mInListener = new AnimatorListener() { @Override public void onAnimationStart (Animator animation) { showNextText(); } @Override public void onAnimationEnd (Animator animation) { float mCurrentWidth = getCurrentViewWidth() + getPaddingEnd() + getPaddingStart(); if (mCurrentWidth >= MAX_WIDTH) { marqueeOffset = MAX_WIDTH - mCurrentWidth; marqueeAnimation.setFloatValues(0 , marqueeOffset); marqueeAnimation.start(); } updateRunning(); } @Override public void onAnimationCancel (Animator animation) { } @Override public void onAnimationRepeat (Animator animation) { } }; private final AnimatorListener mOutListener = new AnimatorListener() { @Override public void onAnimationStart (Animator animation) { if (TruncateAt.MARQUEE == truncateAt) { getCurrentView().setSelected(false ); } } @Override public void onAnimationEnd (Animator animation) { mAnimationIn.start(); } @Override public void onAnimationCancel (Animator animation) { } @Override public void onAnimationRepeat (Animator animation) { } }; private final AnimatorUpdateListener mUpdateListener = new AnimatorUpdateListener() { @Override public void onAnimationUpdate (ValueAnimator animation) { float mCurrentWidth = getCurrentViewWidth(); float factor = (float ) animation.getAnimatedValue(); mCurrentWidth = mCurrentWidth * factor; setCurrentWidth(mCurrentWidth); } }; private final AnimatorUpdateListener marqueeUpdateListener = new AnimatorUpdateListener() { @Override public void onAnimationUpdate (ValueAnimator animation) { setCurrentViewMarginLeft((Float) animation.getAnimatedValue()); } }; private final AnimatorListener marqueeAnimationListener = new AnimatorListener() { @Override public void onAnimationStart (Animator animation) { } @Override public void onAnimationEnd (Animator animation) { updateRunning(); } @Override public void onAnimationCancel (Animator animation) { } @Override public void onAnimationRepeat (Animator animation) { } }; public AutoSizeTextSwither (Context context) { this (context, null ); } public AutoSizeTextSwither (Context context, AttributeSet attrs) { super (context, attrs); init(); } private void init () { setFactory(this ); setInAnimation(null ); setOutAnimation(null ); setClipToPadding(false ); mAnimationIn.setDuration(DEFAULT_DURATION); mAnimationIn.addListener(mInListener); mAnimationIn.setInterpolator(new LinearInterpolator()); mAnimationIn.addUpdateListener(mUpdateListener); mAnimationOut.setDuration(DEFAULT_DURATION); mAnimationOut.addListener(mOutListener); mAnimationOut.setInterpolator(new LinearInterpolator()); mAnimationOut.addUpdateListener(mUpdateListener); marqueeAnimation.setDuration(DEFAULT_DURATION); marqueeAnimation.setInterpolator(new LinearInterpolator()); marqueeAnimation.addUpdateListener(marqueeUpdateListener); marqueeAnimation.addListener(marqueeAnimationListener); } @Override public View makeView () { TextView childTextView = new TextView(getContext()); childTextView.setGravity(Gravity.CENTER_VERTICAL); childTextView.setSingleLine(true ); childTextView.setTextSize(16 ); childTextView.setFocusable(true ); childTextView.setFocusableInTouchMode(true ); childTextView.setEllipsize(truncateAt); childTextView.setTextColor(getContext().getResources().getColor(android.R.color.black)); return childTextView; } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive (Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { mUserPresent = false ; updateRunning(); } else if (Intent.ACTION_USER_PRESENT.equals(action)) { mUserPresent = true ; updateRunning(false ); } } }; @Override protected void onWindowVisibilityChanged (int visibility) { super .onWindowVisibilityChanged(visibility); mVisible = visibility == VISIBLE; updateRunning(false ); } @Override protected void onAttachedToWindow () { super .onAttachedToWindow(); final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); getContext().registerReceiver(mReceiver, filter); if (0 != mContentList.size()) { showNextText(); if (mAutoStart && mContentList.size() > 1 ) { startFlipping(); } } } private final Runnable mFlipRunnable = new Runnable() { @Override public void run () { if (mRunning) { mAnimationOut.start(); postDelayed(mFlipRunnable, mInterval); } } }; @Override protected void onDetachedFromWindow () { super .onDetachedFromWindow(); mVisible = false ; getContext().unregisterReceiver(mReceiver); updateRunning(); } private void updateRunning () { updateRunning(true ); } public void startFlipping () { mStarted = true ; updateRunning(); } public void stopFlipping () { mStarted = false ; updateRunning(); } private void updateRunning (boolean flipNow) { boolean running = mVisible && mStarted && mUserPresent; if (running != mRunning) { if (running) { postDelayed(mFlipRunnable, mInterval); } else { removeCallbacks(mFlipRunnable); } mRunning = running; } } private void setCurrentWidth (float currentWidth) { float mCurrentWidth = currentWidth + getPaddingStart() + getPaddingEnd(); if (mCurrentWidth > MAX_WIDTH) { mCurrentWidth = MAX_WIDTH; } ViewGroup.LayoutParams layoutParam = getLayoutParams(); layoutParam.width = (int ) mCurrentWidth; setLayoutParams(layoutParam); } private int getCurrentViewWidth () { int width = 0 ; TextView mCurrentView = (TextView) getCurrentView(); String text = mCurrentView.getText().toString(); int hash = text.hashCode(); Float measureWidth = mViewSizeCache.get(hash); if (null == measureWidth) { measureWidth = mCurrentView.getPaint().measureText(text) + mCurrentView.getPaddingStart() + mCurrentView.getPaddingEnd(); mViewSizeCache.put(hash, measureWidth); } width = measureWidth.intValue(); return width; } private void setNextChild () { if (mCurrentIndex > mContentList.size() - 1 ) { mCurrentIndex = 0 ; } TextView mNextView = (TextView) getNextView(); final String mContent = mContentList.get(mCurrentIndex++); mNextView.setText(HtmlCompat.fromHtml(mContent, HtmlCompat.FROM_HTML_MODE_LEGACY)); int hash = mContent.hashCode(); Float measureWidth = mViewSizeCache.get(hash); if (null == measureWidth) { measureWidth = mNextView.getPaint().measureText(mContent) + mNextView.getPaddingEnd() + mNextView.getPaddingStart(); mViewSizeCache.put(hash, measureWidth); } MarginLayoutParams param = (MarginLayoutParams) mNextView.getLayoutParams(); if (MAX_WIDTH < measureWidth.intValue() && TruncateAt.MARQUEE == truncateAt) { param.width = MAX_WIDTH - getPaddingStart() - getPaddingEnd(); } else { param.width = measureWidth.intValue(); } mNextView.setLayoutParams(param); showNext(); setCurrentViewMarginLeft(0f ); float originalTextWidth = getCurrentViewWidth(); setCurrentWidth(originalTextWidth); getCurrentView().setOnClickListener(new View.OnClickListener() { @Override public void onClick (View view) { if (null != onItemClickListener) { onItemClickListener.onItemClick(view, mContent, getDisplayedChild()); } } }); } private void setCurrentViewMarginLeft (float leftMargin) { View currentView = getCurrentView(); MarginLayoutParams marginLayoutParam = (MarginLayoutParams) currentView.getLayoutParams(); marginLayoutParam.leftMargin = (int ) leftMargin; currentView.setLayoutParams(marginLayoutParam); } private int dip2px (float dpValue) { float scale = getContext().getResources().getDisplayMetrics().density; return (int ) (dpValue * scale + 0.5f ); } private void showNextText () { setNextChild(); } private void resetInterval () { if (mInterval < mIntervalIn + mIntervalOut) { mInterval = mIntervalIn + mIntervalOut + mInterval; } } public void setIntervalIn (long mIntervalIn) { this .mIntervalIn = mIntervalIn; resetInterval(); } public void setIntervalOut (long mIntervalOut) { this .mIntervalOut = mIntervalOut; resetInterval(); } public void setInterval (long mInterval) { this .mInterval = mInterval; resetInterval(); } public List<String> getContentList () { return mContentList; } public void setContentList (List<String> mContentList) { if (null == mContentList) return ; this .mContentList = mContentList; mViewSizeCache.clear(); showNextText(); } public void setAutoStart (boolean mAutoStart) { this .mAutoStart = mAutoStart; } public void setTruncateAt (TruncateAt truncateAt) { this .truncateAt = truncateAt; } public void setMaxWidth (int maxWidth) { MAX_WIDTH = maxWidth; } public void setOnItemClickListener (OnItemClickListener onItemClickListener) { this .onItemClickListener = onItemClickListener; } }
注意设置高度用:layoutParam.height = ViewGroup.LayouParam.MATCH_PARENT
高级进阶
刚开始想通过ViewFlipper来实现,一时半会没有好的思路就先用上面的TextSwticher来显示。
后来通过自研,多次测试调优终于实现了ViewFlipper动态调整的效果。
代码如下,仅供参考学习。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 package com.dxmat.test.dxmtest;import android.animation.Animator;import android.animation.Animator.AnimatorListener;import android.animation.ObjectAnimator;import android.animation.ValueAnimator;import android.animation.ValueAnimator.AnimatorUpdateListener;import android.content.Context;import android.graphics.Canvas;import android.util.ArrayMap;import android.util.AttributeSet;import android.util.Log;import android.view.View;import android.view.ViewGroup;import android.view.animation.LinearInterpolator;import android.widget.ViewFlipper;class AutoSizeViewFlipper extends ViewFlipper { private static final int DEFAULT_DURATION = 500 ; private int MAX_WIDTH = 800 ; private int parentWidthMeasureSpec; private int parentHeightMeasureSpec; private ArrayMap<Integer, Integer> childWidthCache = new ArrayMap<>(3 ); private ValueAnimator outAnimator = ObjectAnimator.ofFloat(1 , 0 ); private ValueAnimator inAnimator = ObjectAnimator.ofFloat(0 , 1 ); private final AnimatorUpdateListener updateWidthListener = new AnimatorUpdateListener() { @Override public void onAnimationUpdate (ValueAnimator animation) { int mCurrentWidth = getCurrentViewWidth(); float factor = (float ) animation.getAnimatedValue(); mCurrentWidth = (int ) (mCurrentWidth * factor); adjustParentWidth(mCurrentWidth); } }; private final AnimatorListener outListener = new AnimatorListener() { @Override public void onAnimationStart (Animator animation) { } @Override public void onAnimationEnd (Animator animation) { manualShowNext(); inAnimator.start(); } @Override public void onAnimationCancel (Animator animation) { } @Override public void onAnimationRepeat (Animator animation) { } }; private final AnimatorListener inListener = new AnimatorListener() { @Override public void onAnimationStart (Animator animation) { } @Override public void onAnimationEnd (Animator animation) { float mCurrentWidth = getCurrentViewWidth() + getPaddingEnd() + getPaddingStart(); if (mCurrentWidth >= MAX_WIDTH) { } } @Override public void onAnimationCancel (Animator animation) { } @Override public void onAnimationRepeat (Animator animation) { } }; public AutoSizeViewFlipper (Context context) { this (context, null ); } public AutoSizeViewFlipper (Context context, AttributeSet attrs) { super (context, attrs); init(); } private void init () { setInAnimation(null ); setOutAnimation(null ); inAnimator.setDuration(DEFAULT_DURATION); inAnimator.addListener(inListener); inAnimator.setInterpolator(new LinearInterpolator()); inAnimator.addUpdateListener(updateWidthListener); outAnimator.setDuration(DEFAULT_DURATION); outAnimator.addListener(outListener); outAnimator.setInterpolator(new LinearInterpolator()); outAnimator.addUpdateListener(updateWidthListener); post(new Runnable() { @Override public void run () { View v = getCurrentView(); Integer w = childWidthCache.get(v.hashCode()); if (w != null ) { adjustParentWidth(w); } } }); } @Override public void setFlipInterval (int milliseconds) { if (milliseconds < 3 * DEFAULT_DURATION) { int flip = 3 * DEFAULT_DURATION + milliseconds; super .setFlipInterval(flip); } else { super .setFlipInterval(milliseconds); } } @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { super .onMeasure(widthMeasureSpec, heightMeasureSpec); parentWidthMeasureSpec = widthMeasureSpec; parentHeightMeasureSpec = heightMeasureSpec; } @Override protected void onAttachedToWindow () { super .onAttachedToWindow(); } public void measureChildWidth (View child) { Integer width = childWidthCache.get(child.hashCode()); child.measure(0 , 0 ); int measuredWidth = child.getMeasuredWidth(); if (width == null || measuredWidth != width) { childWidthCache.put(child.hashCode(), width); } } @Override public void onViewAdded (View child) { super .onViewAdded(child); Integer width = childWidthCache.get(child.hashCode()); child.measure(0 , 0 ); int measuredWidth = child.getMeasuredWidth(); if (width == null || measuredWidth != width) { childWidthCache.put(child.hashCode(), measuredWidth); } } @Override public void onViewRemoved (View child) { super .onViewRemoved(child); childWidthCache.remove(child.hashCode()); } private void manualShowNext () { int index = getDisplayedChild(); setDisplayedChild(index + 1 ); } private void manualShowPrevious () { int index = getDisplayedChild(); setDisplayedChild(index - 1 ); } @Override public void showNext () { Log.e("ViewFlipper" , "cur width" + getCurrentViewWidth()); outAnimator.start(); } @Override public void showPrevious () { outAnimator.start(); } private int getCurrentViewWidth () { View currentView = getCurrentView(); if (null == currentView) return 0 ; Integer width = childWidthCache.get(currentView.hashCode()); return width == null ? 0 : width; } private void adjustParentWidth (int width) { int lastWidth = width + getPaddingEnd() + getPaddingStart(); if (lastWidth > MAX_WIDTH) { lastWidth = MAX_WIDTH; } ViewGroup.LayoutParams param = getLayoutParams(); param.width = lastWidth; setLayoutParams(param); } }