Harshal Kshatriya
Harshal Kshatriya

Reputation: 5850

How do I add a LinearLayout inside a RelativeLayout, programmatically?

I've a RelativeLayout which consists of an ImageView and TextView. Now, to this RelativeLayout I want to add a LinearLayout, which should be aligned below the TextView. Right now, the LinearLayout is added to the RelativeLayout, but it is not aligned below the TextView. Here is my code :

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);
}

I have one doubt here. Does RelativeLayout.BELOW work, when it is applied to a different kind of layout, nested in a RelativeLayout? Thanks.

Upvotes: 0

Views: 5325

Answers (1)

a.ch.
a.ch.

Reputation: 8380

Yes, RelativeLayout.BELOW will work. It is recognized by parent RelativeLayout no matter what the child view class is.

According to your problem, I suppose that RelativeLayout is behaving that way because you've set fill_parent for your TextView movieNameTextView's layout width.

Upvotes: 3

Related Questions