How to dynamically add a widget in android?

I want to add a button widget to a linear layout dynamically but it does not seem to work. In my sum_example.xml file I already have added three widgets in a linear layout that is the root layout.

    //Finding the layout
        LinearLayout linear = (LinearLayout) findViewById(R.id.sum_example_root);
        //Creating a widget
        Button button = new Button(this);
        //Setting the required parameters of widget
        button.setLayoutParams(new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        //Setting optional parameters of widget
        button.setId(R.id.added_btn_1);
        button.setText("I am added");
        button.setTextColor(0x000000);
        button.setBackgroundColor(0x00ff00);
        button.setOnClickListener(this::sum);
        //Adding the widget to the layout
        linear.addView(button);

Answer

You are on the right track but the Problem is your Colors arguments.

 button.setText("I am added");
 button.setTextColor(Color.BLACK);
 button.setBackgroundColor(Color.MAGENTA);

Try using Color Class Constants instead as I have done above.

//You don't need this
button.setId(R.id.added_btn_1);

Also don’t add set an Id on a button since you are not adding it to the View Hierachy. The name identifier should suffice