Android以编程方式将相对布局置于相对布局下方

时间:2014-02-21 23:01:19

标签: android relativelayout

您好我在尝试将此相对布局放置在另一个相对布局下方时遇到了麻烦。在我的Activity中,我有一个NavBar(RelativeLayout),它与活动的顶部对齐。我想以编程方式将我的TitleBar(RelativeLayout)放在此下面。

这是我的onCreate方法,我分配了NavBar和TitleBar并将它们添加到我的Activity中。 NavBar在活动的顶部正确对齐,但是,TitleBar也与活动的顶部对齐。我希望TitleBar的顶部与NavBar的底部对齐,以便它放在NavBar下面。

    super.onCreate(bundle);

    Context context = getApplicationContext();
    RelativeLayout.LayoutParams params;

    //navbar
    this.navBar = new BINavBar(context);
    relativeLayout.addView(this.navBar);

    params = (LayoutParams)this.navBar.getLayoutParams();
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    this.navBar.setLayoutParams(params);

    //titleBar
    this.titleBar = new BITitleBar(context);
    relativeLayout.addView(this.titleBar);

    params = (LayoutParams)this.titleBar.getLayoutParams();
    params.addRule(RelativeLayout.BELOW, R.id.BINavBar_layout);
    this.titleBar.setLayoutParams(params);

2 个答案:

答案 0 :(得分:0)

我感觉您正在创建的视图的ID未使用您尝试使用的ID。试试这个:

//params.addRule(RelativeLayout.BELOW, R.id.BINavBar_layout);
params.addRule(RelativeLayout.BELOW, this.navBar.getId());

答案 1 :(得分:0)

我认为您实际上并未设置导航栏的ID。请尝试以下方法:

super.onCreate(bundle);

Context context = getApplicationContext();
RelativeLayout.LayoutParams params;

//navbar
this.navBar = new BINavBar(context);
relativeLayout.addView(this.navBar);

params = (LayoutParams)this.navBar.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
this.navBar.setLayoutParams(params);
this.navBar.setId(R.id.BINavBar_layout); // this is the change

//titleBar
this.titleBar = new BITitleBar(context);
relativeLayout.addView(this.titleBar);

params = (LayoutParams)this.titleBar.getLayoutParams();
params.addRule(RelativeLayout.BELOW, this.navBar.getId()); // this should use navBar's id
this.titleBar.setLayoutParams(params);

请注意,您可能需要自己设置ID。您确定R.id.BINavBar_layout存在吗?如果没有,请尝试使用以下功能:View.generateViewId()