I want to start a Thread when I click a Button. That Thread moves a View down every second, but it doesn't work. Here's the code:
public class MainActivity extends Activity {
private boolean juegoEmpezado = false;
private int clicks = 0;
private int margenTop = 20;
private int crecimientoMargen = 10;
private int velocidadDeCrecimiento = 1000;
private LayoutParams parametrosLayout;
private TextView item;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = (TextView)findViewById(R.id.textView1);
item.setText("asasas");
parametrosLayout = (LayoutParams) item.getLayoutParams();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void empezarJuego(View v) {
juegoEmpezado = true;
empezar();
}
public void empezar() {
runOnUiThread(new Runnable() {
@Override
public void run() {
while(juegoEmpezado) {
try {
Thread.sleep(velocidadDeCrecimiento);
parametrosLayout.topMargin = margenTop;
margenTop += crecimientoMargen;
item.setLayoutParams(parametrosLayout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
The empezar()
method is the method that fires when I click the Button.
It doesn't work. I saw this question: Android "Only the original thread that created a view hierarchy can touch its views."
But it can't help me. Can you tell me where is the problem?