I am working in an app that shows different cars and the user needs to choose one. When you press on next the car moves out of the screen and the new one comes in.
My resources are:
- Car's body
- Car's wheel
(I need them to be separated because when the car moves I need to rotate the wheels)
I wanted to avoid AbsoluteLayout
so my CarView
extends `RelativeLayout. Here's the code:
public class CarView extends RelativeLayout {
private ImageView mBody;
private ImageView mLeftWheel;
private ImageView mRightWheel;
private float mScale;
public CarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CarView(Context context) {
super(context);
}
public void initView(Car car) {
mScale = getContext().getResources().getDisplayMetrics().density;
Context ctx = getContext();
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
mBody = new ImageView(ctx);
mBody.setLayoutParams(params);
mBody.setImageResource(R.drawable.car_body);
addView(mBody);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
mLeftWheel = new ImageView(ctx);
mLeftWheel.setLayoutParams(params);
mLeftWheel.setImageResource(R.drawable.car_wheel);
mLeftWheel.setPadding(0, dpToPx(79), dpToPx(188), 0);
addView(mLeftWheel);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
mRightWheel = new ImageView(ctx);
mRightWheel.setLayoutParams(params);
mRightWheel.setImageResource(R.drawable.car_wheel);
mRightWheel.setPadding(dpToPx(203), dpToPx(75), 0, 0);
addView(mRightWheel);
}
public void startMoving() {
RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(900L);
rotateAnimation.setRepeatCount(Animation.INFINITE);
mLeftWheel.startAnimation(rotateAnimation);
mRightWheel.startAnimation(rotateAnimation);
}
private int dpToPx(float dp) {
return (int) (dp * mScale + 0.5f);
}
}
Basically what I am doing is placing the body of the car and then using padding to place the wheels where they should be.
After reading this android developer's thread I notice that RotateAnimation
rotates the whole view including the padding making the wheels to do some strange movement.
How should I fix this?
Can you think of a better way to place the wheels ImageView
instead of using padding?
Another issue I have is that in a certain point I want the wheels to stop moving, but the method cancel() in Animation
is Since: API Level 8 and I need this to work on 1.5. How should I stop the rotation?