So I'm creating a program which will randomly spawn circles on the screen every 5 seconds. I had it working by just displaying 1 circle but when I tried to loop in the onCreate method to draw multiple circles, I got compiler errors and I have no idea what to do now, been stuck for 30 minutes. Here is my code and the main error. Any help will be appreciated.
public class RandomCircles extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
setContentView(new MyView(R.layout.activity_random_circles);
}
}, 0, 5 * 1000L);//5 seconds
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_random_circles, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class MyView extends View {
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
//800, 1162
Random rand = new Random();
double x = rand.nextInt(getWidth());
if(getWidth() - x < 100)
x -= 100;
else if(getWidth() - x > getWidth() - 100)
x += 100;
double y = rand.nextInt(getHeight());
if(getHeight() - y < 100)
y -= 100;
else if(getHeight() - x > getHeight() - 100)
y += 100;
int radius;
radius = 100;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x, y, radius, paint);
}
}
Your
MyView
constructor seeks aContext
as parameter, but you are passingR.layout.activity_random_circles
which is basically a auto-generated int value mapped to your layout xml file inres/layout
. Try passingRandomCircles.this
instead that refers to yourActivity
context