Creating android activity programatically


In android an activity can be created in two ways, first one is simply using the android xml file in the layout folder of your android project and another ways is to create all these views and view groups for the activity by writing programs or code. So in this post i explain how to create an android layout dynamically. I explain it using the following example. please watch the above video for getting more information about this.

MainActivity.java

  1. package com.programlayout;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.Menu;
  5. import android.widget.Button;
  6. import android.widget.LinearLayout;
  7. import android.widget.LinearLayout.LayoutParams;
  8. import android.widget.TextView;
  9. public class MainActivity extends Activity {
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. // setContentView (R.layout.activity_main);
  14. android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
  15. LinearLayout layout = new LinearLayout(this);
  16. layout.setOrientation(LinearLayout.VERTICAL);
  17. TextView txt = new TextView(this);
  18. txt.setText("Demo text view");
  19. txt.setLayoutParams(params);
  20. layout.addView(txt);
  21. Button b1 = new Button(this);
  22. b1.setText("Demo button 1");
  23. b1.setLayoutParams(params);
  24. layout.addView(b1);
  25. Button b2 = new Button(this);
  26. b2.setText("Demo button 2");
  27. b2.setLayoutParams(params);
  28. layout.addView(b2);
  29. LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
  30. this.addContentView(layout, layoutparams);
  31. }
  32. @Override
  33. public boolean onCreateOptionsMenu(Menu menu) {
  34. // Inflate the menu; this adds items to the action bar if it is present.
  35. getMenuInflater().inflate(R.menu.main, menu);
  36. return true;
  37. }
  38. }