Procedure
- Start Eclipse IDE.
- Create a new project.
- Create two Java files, one is AnimationUsingView.java and the second is MyView.java.
- Create an activity_animation_using_view.xml file for layout design.
- In MyView.java file add an image using BitmapFactory and then in the onDraw function use a canvas with drawLine,drawBitmap, and drawColor.
- In the AnimationUsingView.java file extends with Activity and declares a variable of MyView type then add animation_using_view in onCreateOptionsMenu.
The code is given below.
MyView.java
- package a.v;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.view.View;
- public class MyView extends View {
- Bitmap ball;
- float change = 0;
- public MyView(Context context) {
- super(context);
- ball = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- Paint pi = new Paint();
- pi.setColor(Color.YELLOW);
- pi.setStrokeWidth(45);
- canvas.drawColor(Color.RED);
- canvas.drawBitmap(ball, canvas.getWidth() / 2, change, null);
- canvas.drawLine((canvas.getWidth() / 2) + 20, 0, (canvas.getWidth() / 2) + 20, change, pi);
- if (change < canvas.getHeight()) {
- change += 5;
- } else {
- change = 0;
- }
- invalidate();
- }
- }
AnimationUsingView.java
- package a.v;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- public class AnimationUsingView extends Activity {
- MyView a1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- a1 = new MyView(getApplicationContext());
- setContentView(a1);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.animation_using_view, menu);
- return true;
- }
- }
activity_animation_using_view.xml
- <RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
-
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".AnimationUsingView" >
-
- </RelativeLayout>
Output