Advertisement

header ads

Android Studio Tutorial - Layout/ Widgets Dynamically



This Example demonstrate how to add Layout and widgets - TextView, EditText, Button dynamically. This also demonstrate how to perform arithmetic operations by reading data from the EditText and Click listener event of Button. This is also demonstrate that keyboard input style with numbers only.



So in this program, demonstrate how to add TextView, EditText and Button Widget and add them into layout using .addView() method.

This project returns sum of 1 to entered number in a series.

Also demonstrate how to use looping structure and conditional statements in .java class

Here is the code of the program


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout layout = new LinearLayout(this);
        LinearLayout myLayout = new LinearLayout(this);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        final EditText num = new EditText(this);
        num.setInputType(InputType.TYPE_CLASS_NUMBER);
        num.setHint("Enter Valid Integer Number...");


        Button mySum = new Button(this);

        final TextView myOut = new TextView(this);
        myOut.setText("\n\nThis program returns sum of series.." + "\n\n Ex. if you enter 5, \nIt will perform 1+2+3+4+5 = 15");

        mySum.setText("Sum of Series");
        mySum.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Integer number = Integer.parseInt(num.getText().toString());
                Integer output = 0;
                if(number > 0 ){
                    for(int i=1; i<= number; i++)
                        output = output + i;
                    myOut.setText("Sum of Series: " + output.toString());
                }
            }
        }); // end of click listener event

        myLayout.addView(num);
        myLayout.addView(mySum);
        myLayout.addView(myOut);

        layout.addView(myLayout);
        setContentView(layout);
    }

Deploy this program to your android device or android virtual device and Test it. If you have any Questions feel free to comment them in the comment section. 

Post a Comment

0 Comments