Changing position of a button

2019-01-12 06:46发布

I have one button in an AbsoluteLayout in an XML file. From there I am able to set the (x,y) position of the button.

How can I get and set the (x,y) coordinates of the button programmatically?

Thanks all.

4条回答
We Are One
2楼-- · 2019-01-12 06:56

The answer you're looking for is in LayoutParams. Firstly, I'd suggest not using AbsoluteLayout -- it's deprecated -- and using something else, maybe a FrameLayout, and just using the left and top margins as your x and y offsets.

However, to answer your question:

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

Or alternatively:

Button button = (Button)findViewById(R.id.my_button);
button.setLayoutParams(new AbsoluteLayout.LayoutParams(
    AbsoluteLayout.LayoutParams.FILL_PARENT, AbsoluteLayout.LayoutParams,
    myNewX, myNewY));
查看更多
甜甜的少女心
4楼-- · 2019-01-12 07:03

You have to get a reference to you button, for example by calling findViewById(). When you got the reference to the button you can set the x and y value with button.setX() and button.setY().

....
Button myButton = (Button) findViewById(R.id.<id of the button in the layout xml file>);
myButton.setX(<x value>);
myButton.setY(<y value>);
....
查看更多
可以哭但决不认输i
5楼-- · 2019-01-12 07:07

hummm u can try this. . . Is there an easy way to add a border to the top and bottom of an Android View? Just go threw this site u will get the Sollution. If not then reply to me. And if its help u then give me a vote. Thanks.

查看更多
登录 后发表回答