Так что я создаю программу, которая будет случайным образом создавать круги на экране каждые 5 секунд. Я работал, просто отображая один круг, но когда я попытался зациклиться на методе onCreate, чтобы нарисовать несколько кругов, у меня появились ошибки компилятора, и я понятия не имею, что делать сейчас, застрял в течение 30 минут. Вот мой код и основная ошибка. Любая помощь будет оценена.Looping in onCreate method
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);
}
}
Спасибо, это работает. Тем не менее, он отображает только один круг и не повторяет их сейчас. Это своего рода не по теме, но любые идеи по этому поводу? – Sygnerical
Как насчет того, что у вас есть фиктивный файл макета, установите идентификатор в корневой макет (скажем, 'android: id =" @ + id/root_layout "и в' onCreate' вы 'setContentView' в этот макет. ваш таймер, вы можете получить контекст этого корневого представления 'LinearLayout layout = (LinearLayout) findViewById (R.id.root_layout);' и добавить к нему свой 'layout.addView (новый MyView (...))' – Mithun