如何以编程方式在RelativeLayout中添加LinearLayout?

时间:2012-04-09 07:45:22

标签: android android-layout

我有一个RelativeLayout,它由ImageView和TextView组成。现在,对于这个RelativeLayout,我想添加一个LinearLayout,它应该在TextView下面对齐。现在,LinearLayout被添加到RelativeLayout,但它没有在TextView下面对齐。这是我的代码:

void addRatingToImage(RelativeLayout relativelLayout, Movies movieObject) {
    ImageView ratingImageView;
    LinearLayout ratingLayout = new LinearLayout(mContext);
    ratingLayout.setOrientation(LinearLayout.HORIZONTAL);

    double roundedRating = roundUpRating(Double.parseDouble(movieObject.mRating));
    for(int i = 0; i < 5; i++) {                        //TODO: Check 
        ratingImageView = new ImageView(mContext);
        if(i < roundedRating) {
            ratingImageView.setBackgroundResource(R.drawable.star_2);

            ratingLayout.addView(ratingImageView);
        }
        else {
            ratingImageView.setBackgroundResource(R.drawable.star_1);
            ratingLayout.addView(ratingImageView);
        }

    }

    RelativeLayout.LayoutParams ratingLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    TextView movieNameTextView = (TextView)relativelLayout.getChildAt(2);
    ratingLayoutParams.addRule(RelativeLayout.BELOW, movieNameTextView.getId());

    ratingLayout.setLayoutParams(ratingLayoutParams);

    relativelLayout.addView(ratingLayout);
}

我有一个疑问。 RelativeLayout.BELOW在应用于不同类型的布局时是否有效,嵌套在RelativeLayout中?感谢。

1 个答案:

答案 0 :(得分:3)

是的,RelativeLayout.BELOW可行。无论子视图类是什么,它都由父RelativeLayout识别。

根据您的问题,我认为RelativeLayout表现得那样,因为您为fill_parent的布局宽度设置了TextView movieNameTextView