你可以使用View.getLayoutParam
s从代码中访问 LayoutParams
。你只需要知道你访问的什么LayoutParams
。这通常是通过检查包含的ViewGroup
就能知道。如果它有一个LayoutParams
子类,那你就应该使用这个LayoutParams
类。
在你的案例中它是RelativeLayout.LayoutParams
,你应该使用RelativeLayout.LayoutParams#addRule(int verb)
和RelativeLayout.LayoutParams#addRule(int verb, int anchor)
你可以通过以下代码获得:
RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //使layout更新