2.3.9 Nested Views Codehs ✭

In CodeHS, a view is a rectangular region on the screen that can contain other views or be used to display graphics, text, or other visual elements.

To nest a view, you simply type the new layout tag inside the parent tags.

If the exercise asks you to create a nested horizontal layout, you would write: 2.3.9 nested views codehs

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<!-- This is the NESTED layout -->
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
<!-- These views are inside the nested layout -->
    <TextView ... />
    <TextView ... />
</LinearLayout>
<!-- End of nested layout -->

</LinearLayout>

Now, create a child that sits inside the parent. The key is that its x and y are relative to the parent’s position. If the parent is at (50, 50), and you want the child at the top-left corner of the parent, you set the child’s position to (50, 50) on the canvas, OR you set it relative to the parent.

Wait, careful: In most Canvas-based libraries, add(child) adds to absolute coordinates. To simulate nesting, we manually offset. In CodeHS, a view is a rectangular region

Correct approach: Child position = Parent position + Offset.

// Header child view (inside parent)
var headerView = new Rectangle(260, 50);
headerView.setColor("navy");
headerView.setPosition(parentView.getX() + 20, parentView.getY() + 20);
add(headerView);

Without nesting, every UI element would exist independently, floating on the screen. Changing the position of one item would require recalculating the positions of every other item. Nesting allows you to: &lt;/LinearLayout&gt;

Add the child views to the parent, not directly to main.

// Nesting happens here
profileCard.add(avatar);
profileCard.add(userName);
profileCard.add(followButton);
profileCard.add(buttonText);

This is the "nested" part. The text should sit inside the header view. Again, we calculate its position based on the header’s position.

var titleText = new Text("Dashboard");
titleText.setColor("white");
titleText.setPosition(headerView.getX() + 10, headerView.getY() + 30);
titleText.setFont("16pt Arial");
add(titleText);