MainActivity.java
package edu.byuh.cis.cs203.hellocs203.sys;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LetiView lv = new LetiView(this);
setContentView(lv);
}
}
LetiView.java
package edu.byuh.cis.cs203.hellocs203.sys;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import edu.byuh.cis.cs203.hellocs203.graphics.Duck;
public class LetiView extends View {
private Duck donald;
private boolean init;
public /*static*/ class Timer extends Handler {
public Timer() {
sendMessageDelayed(obtainMessage(), 0);
}
@Override
public void handleMessage(Message m) {
//Log.d("CS203", "Hello, Altair!");
donald.dance();
invalidate();
sendMessageDelayed(obtainMessage(), 100);
}
}
public LetiView(Context c) {
super(c);
init = false;
donald = new Duck(getResources());
Toast t = Toast.makeText(c, "This is another factory example!", Toast.LENGTH_LONG);
t.show();
Timer tim = new Timer();
}
@Override
public void onDraw(Canvas c) {
float w = c.getWidth();
float h = c.getHeight();
if (init == false) {
donald.resize(w);
donald.setPosition(w-donald.width(), 0);
init = true;
}
c.drawColor(Color.GREEN);
donald.draw(c);
}
}
Duck.java
package edu.byuh.cis.cs203.hellocs203.graphics;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import edu.byuh.cis.cs203.hellocs203.R;
public class Duck {
private Bitmap image;
private RectF bounds;
/**
* Create a new duck
* @param res the Android resources object
*/
public Duck(Resources res) {
bounds = new RectF();
image = BitmapFactory.decodeResource(res, R.drawable.duck);
}
/**
* scale the duck to its correct on-screen size
* @param screenWidth the width of the screen in pixels
*/
public void resize(float screenWidth) {
float duckSize = screenWidth * 0.2f;
image = Bitmap.createScaledBitmap(image,
(int)duckSize, (int)duckSize, true);
bounds.set(0,0,duckSize, duckSize);
}
/**
* Draw the duck at its predefined location
* @param c the Android canvas object
*/
public void draw(Canvas c) {
c.drawBitmap(image, bounds.left, bounds.top, null);
}
/**
* Sets the center of the duck to (x,y)
* @param x the new center x coordinate
* @param y the new center y coordinate
*/
public void setPosition(float x, float y) {
bounds.offsetTo(x,y);
}
public float width() {
return bounds.width();
}
public void dance() {
float dx = 5-(float)(Math.random() * 10);
float dy = 5-(float)(Math.random() * 10);
bounds.offset(dx,dy);
}
}