我以前的方法有问题的内存消耗。我改进了它以使用TranslateAnimation。但它有一点LAG(在ProgressBgView.initAnimation方法HACK注释注意)
布局的xml:
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/progress_db_view"
/>
后端:
final ProgressBgView prog = (ProgressBgView) findViewById(R.id.progress_db_view);
prog.setBackgroundAsTile(R.drawable.bg_tile_1);
prog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prog.startAnimation();
}
});
和类:
public class ProgressBgView extends FrameLayout {
private ImageView mProgressImage;
private TranslateAnimation mProgressAnimation;
public ProgressBgView(Context context, AttributeSet attrs) {
super(context, attrs);
mProgressImage = new ImageView(getContext());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
mProgressImage.setLayoutParams(layoutParams);
addView(mProgressImage);
}
public void setBackgroundAsTile(int tileImageResId) {
Bitmap tileBitmap = BitmapFactory.decodeResource(getResources(), tileImageResId);
BitmapDrawable tileRepeatedBitmap = new BitmapDrawable(getResources(), tileBitmap);
tileRepeatedBitmap.setTileModeX(TileMode.REPEAT);
initAnimation(tileBitmap.getWidth());
mProgressImage.setBackgroundDrawable(tileRepeatedBitmap);
}
private void initAnimation(int tileImageWidth) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mProgressImage.getLayoutParams();
layoutParams.setMargins(-tileImageWidth, 0, 0, 0);
// *HACK* tileImageWidth-3 is used because of *lags*(slow pause) in the moment
// of animation END-RESTART.
mProgressAnimation = new TranslateAnimation(0, tileImageWidth - 3, 0, 0);
mProgressAnimation.setInterpolator(new LinearInterpolator());
mProgressAnimation.setDuration(1000);
mProgressAnimation.setRepeatCount(Animation.INFINITE);
}
public void startAnimation() {
mProgressImage.startAnimation(mProgressAnimation);
}
}