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);
Is there开发者_C百科 any way to position b1 in layout1? I want it to float right. Or is the only way to replace the complete layout with a new inflated layout?
Use addRule() methods to position views in relativeLayout. There are 2 methods, one to position relative to container (RelativeLayout itself. Your case) and another to position relative to other views in the container.
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);
精彩评论