Create another page

In the previous section, we wrote a page containing text and buttons in XML. To help developers become familiar with how to create layouts in code, let’s write a second page in code.

In the Project window, open the “entry > SRC > main > Java > com. Example. Myapplication”, right click on the “slice” folder, select “New > Java Class”, Name it “SecondAbilitySlice” and press Enter. There is text on the second page. In the “SecondAbilitySlice” file created in the previous step, add a Text as follows:

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DependentLayout.LayoutConfig;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;

public class SecondAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        // Declare layout
        DependentLayout myLayout = new DependentLayout(this);

        // Set the layout width and height
        myLayout.setWidth(LayoutConfig.MATCH_PARENT);
        myLayout.setHeight(LayoutConfig.MATCH_PARENT);

        // Set the layout background to white
        ShapeElement background = new ShapeElement();
        background.setRgbColor(new RgbColor(255.255.255));
        myLayout.setBackground(background);

        // Create a text
        Text text = new Text(this);
        text.setText("Hi there");
        text.setWidth(LayoutConfig.MATCH_PARENT);
        text.setTextSize(100);
        text.setTextColor(Color.BLACK);

        // Set the layout of the text
        DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
        textConfig.addRule(LayoutConfig.CENTER_IN_PARENT);
        text.setLayoutConfig(textConfig);
        myLayout.addComponent(text);
        super.setUIContent(myLayout); }}Copy the code