5. Develop an animation of a car in android studio which can move after pressing respective arrow keys.
JAVA code:
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
ImageView car;
Button left, right;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
car=findViewById(R.id.car);
left=findViewById(R.id.btn_left);
right=findViewById(R.id.btn_right);
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
car.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rightt
oleft));
}
});
right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
car.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.leftto
right));
}
});
}
}
XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/car"
android:layout_marginTop="250dp"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="100dp"
android:src="@drawable/car"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_left"
android:layout_width="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_height="wrap_content"
android:text="Left"/>
<Button
android:id="@+id/btn_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right"/>
</LinearLayout>
</LinearLayout>
XML code: Right animation
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700" />
</set>
XML code: Left animation
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>