1.自定义继承imageview的view:
public class ShimmerFrameLayout extends AppCompatImageView {
AnimationDrawable animationDrawable;
Runnable runnable;
int delayMillis;
public ShimmerFrameLayout(Context context) {
super(context);
init(context, null);
}
public ShimmerFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ShimmerFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, @Nullable AttributeSet attrs) {
setWillNotDraw(false);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.shimmerStyle);
if (typedArray != null) {
delayMillis = typedArray.getInt(R.styleable.shimmerStyle_delayMillis, 1000);
}
Drawable drawable = getDrawable();
if (drawable != null && drawable instanceof AnimationDrawable) {
animationDrawable = (AnimationDrawable) drawable;
animationDrawable.start();
runnable = new Runnable() {
@Override
public void run() {
if (animationDrawable != null) {
animationDrawable.stop();
animationDrawable.start();
postDelayed(runnable, delayMillis);
}
}
};
}
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
if (runnable != null) {
postDelayed(runnable, delayMillis);
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (runnable != null) {
removeCallbacks(runnable);
}
}
}
2.自定义间隔属性
<declare-styleable name="kwShimmerStyle">
<attr name="delayMillis" format="integer"/>
</declare-styleable>
3.removeallbacks
postDelayed方法和removeCallbacks方法的使用
方法postDelayed的作用是延迟多少毫秒后开始运行,而removeCallbacks方法是删除指定的Runnable对象,使线程对象停止运行。
使用方法:
<cn.shimmer.ShimmerFrameLayout
android:id="@+id/imvg_live_guard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/iv_live_recorded"
android:layout_marginEnd="11dp"
app:delayMillis= "5000"
android:src="@drawable/play_gif"
android:layout_marginRight="11dp"
android:layout_marginTop="10dip"/>
play_gif :
<?xml version="1.0" encoding="UTF-8"?>
<animation-list android:oneshot="true"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:duration="55" android:drawable="@drawable/gif_0"
/>
<item android:duration="55" android:drawable="@drawable/gif_1"
/>
<item android:duration="55" android:drawable="@drawable/gif_2"
/>
</animation-list>