问题
I had seen a couple of examples for setting the relative position through program (from java) for views in android. But in my particular case i have 2 buttons (which are not views) say "button_tag" and "button_rate" which are made via xml and are arranged such as "button_tag" above "button_rate" by default. If at any point of time is there a mechanism by which i can make "button_tag" below "button_rate" dynamically.
<Button
android:id="@+id/button_tag"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="1dp"
android:background="@drawable/img_whitebackground"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:text="@string/string_tag"
android:onClick="click_addscreen" >
</Button>
<Button
android:id="@+id/button_rate"
android:layout_marginTop="1dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="@string/string_rate"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:onClick="click_addscreen"
android:background="@drawable/img_whitebackground" >
</Button>
The xml part of the two buttons are as shown
回答1:
You can use LayoutParams object and add rules to that object as per your requirement. and then setlayoutparam to your button.
For example:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80,80); // size of button in dp
params.addRule(RelativeLayout.LEFT_OF, R.id.btnAdd);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 20, 60);
btnMyLocation.setLayoutParams(params);
回答2:
You can add rules to set position dynamically.
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
p.addRule(RelativeLayout.BELOW, R.id.button_rate);
buttonTag.setLayoutParams(p);
来源:https://stackoverflow.com/questions/31673285/dynamically-changing-the-position-of-a-button-with-respect-to-another-button