【问题标题】:How do I add a LinearLayout inside a RelativeLayout, programmatically?如何以编程方式在 RelativeLayout 中添加 LinearLayout?
【发布时间】:2012-04-09 07:45:22
【问题描述】:

我有一个由 ImageView 和 TextView 组成的 RelativeLayout。现在,我想向这个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 中的不同类型的布局时,它是否有效?谢谢。

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    是的,RelativeLayout.BELOW 可以使用。无论子视图类是什么,它都被父 RelativeLayout 识别。

    根据您的问题,我认为RelativeLayout 的行为方式是因为您为TextView movieNameTextView 的布局宽度设置了fill_parent

    【讨论】:

    • 感谢您告知 RelativeLayout.Below 将起作用。我通过使用RelativeLayout.ALIGN_PARENT_BOTTOM 来解决它,将LinearLayout 与RelativeLayout 对齐,然后使用边距。但是,TextView movieNameTextView 设置为 WRAP_CONTENT。我会弄清楚。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多