最近我试图创建一个类似于我很久以前制作的java项目的应用程序。每当我点击一个按钮时,它会画一个随机颜色的圆圈,然后在窗口中移动它。
我有两个分支:一个用于线程,另一个用于UI。在UI中,我处理点击事件并为每个圆创建一个线程,如下所示:
Hilo Carrete = new Hilo();
public void actionPerformed (ActionEvent e) {
if (e.getSource() == Circulo) {
Carrete = new Hilo(100, 200, "C");
add(Carrete);
repaint();
}
“Hilo”是我的线程类,Circulo是按钮的文本。
我想在android中使用onTouchEvent制作类似的东西,但我不知道我是如何在android中添加“添加(Carrete)”的。如何向视图添加新线程?
这是我的源代码:
public class MainActivity extends AppCompatActivity {
Hilo vista;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(vista);
vista = new Hilo(this);
vista.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float X = event.getX();
float Y = event.getY();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
v.postInvalidate();
v.draw(new Canvas().drawCircle(X, Y, 30, ););
}
return true;
}
});
}
class Hilo extends View implements Runnable {
Thread hilo;
int X = 0;
int Y = 0;
int colorPelota;
int Xmax, Ymax;
boolean horizontal, vertical;
Random colores;
//Color colorFigura;
Paint fondo, bolita;
public Hilo(Context contexto) {
super(contexto);
fondo = new Paint();
bolita = new Paint();
colores = new Random();
int r = colores.nextInt(255);
int g = colores.nextInt(255);
int b = colores.nextInt(255);
colorPelota = Color.rgb(r, g, b);
fondo.setColor(Color.WHITE);
bolita.setColor(colorPelota);
if(Math.random() <= 0.5) {horizontal = true;}
else {horizontal = false;}
if(Math.random() <= 0.5) {vertical = true;}
else {vertical = false;}
hilo = new Thread(this);
hilo.start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPaint(fondo);
canvas.drawCircle(X, Y, 30, bolita);
this.draw(new Canvas().drawCircle(););
}
@Override
public void run() {
while(true) {
try{
if(X == 50) horizontal = false;
else if(X >= Xmax) horizontal = true;
if(Y == 50) vertical = false;
else if(Y >= Ymax) vertical = true;
if((horizontal == false) && (vertical == false)) {
X++;
Y--;
}
else if((horizontal == false) && (vertical == true)) {
X++;
Y++;
}
else if((horizontal == true) && (vertical == false)) {
X--;
Y--;
}
else if((horizontal == true) && (vertical == true)) {
X--;
Y++;
}
hilo.sleep(10);
}
catch(InterruptedException ie) {
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
X = w / 2;
Y = 0;
Ymax = h;
Xmax = w;
}
/* @Override
public boolean onTouchEvent(MotionEvent event) {
float X = event.getX();
float Y = event.getY();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
postInvalidate();
}
return true;
}*/
}
提前致谢。