2011-04-13 14 views
6

Tengo un botón en un AbsoluteLayout en un archivo XML. Desde allí, puedo establecer la posición (x, y) del botón.Cambio de posición de un botón

¿Cómo puedo obtener y establecer las coordenadas (x, y) del botón mediante programación?

Gracias todos.

Respuesta

9

Tienes que obtener una referencia a tu botón, por ejemplo, llamando al findViewById(). Cuando obtenga la referencia al botón, puede establecer el valor xey con el botón. setX() y botón. setY().

.... 
Button myButton = (Button) findViewById(R.id.<id of the button in the layout xml file>); 
myButton.setX(<x value>); 
myButton.setY(<y value>); 
.... 
+0

se dice que el método setX (int) no está definido para el tipo Button. – WISH

+0

Mh, eso es raro. La clase Button amplía la clase View y allí puede encontrar los dos métodos setX() y setY(). Pruebe esto en su lugar: vea myButton = (Ver) findViewById (R.id. ); – Flo

+0

tenemos métodos para todas las propiedades, pero no tenemos ningún método para configurar xey para los botones u otros widgets. :( – WISH

5

La respuesta que está buscando es en LayoutParams. En primer lugar, sugeriría no usando AbsoluteLayout - está en desuso - y usando algo más, tal vez un FrameLayout, y simplemente usando los márgenes izquierdo y superior como sus compensaciones xey.

Sin embargo, para responder a su pregunta:

Button button = (Button)findViewById(R.id.my_button); 
AbsoluteLayout.LayoutParams absParams = 
    (AbsoluteLayout.LayoutParams)button.getLayoutParams(); 
absParams.x = myNewX; 
absParams.y = myNewY; 
button.setLayoutParams(absParams); 

O, alternativamente:

Button button = (Button)findViewById(R.id.my_button); 
button.setLayoutParams(new AbsoluteLayout.LayoutParams(
    AbsoluteLayout.LayoutParams.FILL_PARENT, AbsoluteLayout.LayoutParams, 
    myNewX, myNewY)); 
Cuestiones relacionadas