applibgroup / HarmonyOS-Knowledgebase

This repository contains code samples of HarmonyOS Training
Apache License 2.0
17 stars 6 forks source link

How to add a component like a button, programmatically from the java code instead of adding it from XML? #40

Closed anshulgoel72 closed 3 years ago

anshulgoel72 commented 3 years ago

Describe the query

I want to add a button programmatically from the java code rather than adding it from the XML file. How can I do that?

Create the query with harmonyos tag in stackoverflow and share the link here:

https://stackoverflow.com/questions/68588836/how-to-add-a-component-like-a-button-programmatically-from-the-java-code-instea

Additional information

Developer Platform: Windows
DevEco Studio version: 2.1.0.303
SDK API version: 5
SDK version: 2.1.1.21
Device: Not Required
Device OS version: Not Required

GowthamRayar commented 3 years ago

First step is to instantiate button inside onStart(), later add the instantiated button to the ComponentContainer or setUIContent();

 @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        Button button = new Button(MainAbilitySlice.this);
        setUIContent(button);
    }