I have a toggleButton I want to change its location (in runtime, not in layout XML) according to user preference. I looked and all I found was AbsoluteLayout which is not what I want (I need relative to screen edges). Is there a way to do so?
Asked
Active
Viewed 229 times
1 Answers
1
You can use a RelativeLayout
and set your toggleButton
relatively to other View
s in the Layout
.
Take a look at this post on how it's done:
How to lay out Views in RelativeLayout programmatically?
Example:
RelativeLayout layout = new RelativeLayout(this);
TextView tv2 = new TextView(this);
tv2.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF, tv2.getId());
layout.addView(tv2, lp);
To edit the margins for the view use the LayoutParams object like so:
lp.setMargins(left, top, right, bottom);
-
Thanks, I read that , but i still have some parts missing : 1. The layout will save rules i don't overwrite ? 2. How can i set an object with 'marginTop' for example ? i didn't find this command in the 'RelativeLayout.' – SagiLow Mar 28 '13 at 15:12
-
to add Margin top you need to spicify the margins in the layoutParam parameter like this: lp.setMargins(left, top, right, bottom); – Emil Adz Mar 28 '13 at 15:14
-
what do you mean by rules you don't overwrite? – Emil Adz Mar 28 '13 at 15:15
-
I still can't understand how i can set my image to be I.E. 50 px from top 40 px from left ? – SagiLow Mar 28 '13 at 15:27
-
first of all don't ever work with pixels... it will cause you problems in different sized screens. to your question you can add you view to be right of parent, and under parent and then set the margins for left and top to 40 and 50 respectively. – Emil Adz Mar 28 '13 at 15:33
-
I did the following after initializing the lp (my object is m_lock), `lp.setMargins(50, 40, 0, 0);` and `lp.addRule(RelativeLayout.RIGHT_OF, m_lock.getId());` after that i added the view... no change for the object. – SagiLow Mar 28 '13 at 15:42