Button b1 = new Button(this);
b1.setText(R.string.hello);
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.top_menu);
//android:layout_alignParentRight=true
layout1.addView(b1);
有没有办法在layout1中定位b1?我想让它漂浮正确。或者是用新的膨胀布局替换整个布局的唯一方法?
答案 0 :(得分:2)
使用addRule()方法在relativeLayout中定位视图。有两种方法,一种是相对于容器的位置(RelativeLayout本身。你的情况),另一种是相对于容器中其他视图的位置。
Button b1 = new Button(this);
b1.setText(R.string.hello);
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.top_menu);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // Relative layout parameters which specify how the child view will be sized (wrap_content in our case)
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // addRule to position it how you need it
layout1.addView(b1, params);