Android:以编程方式对齐父级底部+底部边距

时间:2014-08-25 14:11:12

标签: android android-layout android-relativelayout

如何以编程方式添加与父元素底部对齐的RelativeLayout,并在同一RelativeLayout中添加边距或填充?

示例:

enter image description here

2 个答案:

答案 0 :(得分:39)

以下是如何做到的:

// Get the parent layout
RelativeLayout parent = (RelativeLayout) findViewById(R.id.parent);

// Create your custom layout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Create LayoutParams for it // Note 200 200 is width, height in pixels
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(200, 200);
// Align bottom-right, and add bottom-margin
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.bottomMargin = 100;

relativeLayout.setLayoutParams(params);
relativeLayout.setBackgroundColor(Color.BLUE);
// Add the custom layout to your parent layout
parent.addView(relativeLayout);

答案 1 :(得分:1)

你可以试试这个在我的情况下工作:

RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) view.getLayoutParams();
                                // position on right bottom
                                rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
                                rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
                                rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                                rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
相关问题